diff --git a/docs/developer/architecture/core/index.asciidoc b/docs/developer/architecture/core/index.asciidoc index 48595690f9784..4a86c90cf8c10 100644 --- a/docs/developer/architecture/core/index.asciidoc +++ b/docs/developer/architecture/core/index.asciidoc @@ -421,29 +421,25 @@ the request handler context: [source,typescript] ---- -import type { CoreSetup, IScopedClusterClient } from 'kibana/server'; +import type { CoreSetup, RequestHandlerContext, IScopedClusterClient } from 'kibana/server'; -export interface MyPluginContext { - client: IScopedClusterClient; -} - -// extend RequestHandlerContext when a dependent plugin imports MyPluginContext from the file -declare module 'kibana/server' { - interface RequestHandlerContext { - myPlugin?: MyPluginContext; - } +interface MyRequestHandlerContext extends RequestHandlerContext { + myPlugin: { + client: IScopedClusterClient; + }; } class MyPlugin { setup(core: CoreSetup) { const client = core.elasticsearch.createClient('myClient'); - core.http.registerRouteHandlerContext('myPlugin', (context, req, res) => { + core.http.registerRouteHandlerContext('myPlugin', (context, req, res) => { return { client: client.asScoped(req) }; }); - const router = core.http.createRouter(); + const router = core.http.createRouter(); router.get( { path: '/api/my-plugin/', validate: … }, async (context, req, res) => { + // context type is inferred as MyPluginContext const data = await context.myPlugin.client.asCurrentUser('endpoint'); } ); diff --git a/docs/development/core/server/kibana-plugin-core-server.httpresources.md b/docs/development/core/server/kibana-plugin-core-server.httpresources.md index cb3170e989e17..25acffc1a040f 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpresources.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpresources.md @@ -16,5 +16,5 @@ export interface HttpResources | Property | Type | Description | | --- | --- | --- | -| [register](./kibana-plugin-core-server.httpresources.register.md) | <P, Q, B>(route: RouteConfig<P, Q, B, 'get'>, handler: HttpResourcesRequestHandler<P, Q, B>) => void | To register a route handler executing passed function to form response. | +| [register](./kibana-plugin-core-server.httpresources.register.md) | <P, Q, B, Context extends RequestHandlerContext = RequestHandlerContext>(route: RouteConfig<P, Q, B, 'get'>, handler: HttpResourcesRequestHandler<P, Q, B, Context>) => void | To register a route handler executing passed function to form response. | diff --git a/docs/development/core/server/kibana-plugin-core-server.httpresources.register.md b/docs/development/core/server/kibana-plugin-core-server.httpresources.register.md index fe3803a6ffe52..ee9569aeb37b4 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpresources.register.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpresources.register.md @@ -9,5 +9,5 @@ To register a route handler executing passed function to form response. Signature: ```typescript -register: (route: RouteConfig, handler: HttpResourcesRequestHandler) => void; +register: (route: RouteConfig, handler: HttpResourcesRequestHandler) => void; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.httpresourcesrequesthandler.md b/docs/development/core/server/kibana-plugin-core-server.httpresourcesrequesthandler.md index 20f930382955e..49854ac003860 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpresourcesrequesthandler.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpresourcesrequesthandler.md @@ -9,7 +9,7 @@ Extended version of [RequestHandler](./kibana-plugin-core-server.requesthandler. Signature: ```typescript -export declare type HttpResourcesRequestHandler

= RequestHandler; +export declare type HttpResourcesRequestHandler

= RequestHandler; ``` ## Example diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.createrouter.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.createrouter.md index 89b9325145652..f009dd3fc2b16 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.createrouter.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.createrouter.md @@ -9,7 +9,7 @@ Provides ability to declare a handler function for a particular path and HTTP re Signature: ```typescript -createRouter: () => IRouter; +createRouter: () => IRouter; ``` ## Remarks diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md index 474dc6b7d6f28..dbc2a516fa17b 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md @@ -84,7 +84,7 @@ async (context, request, response) => { | [auth](./kibana-plugin-core-server.httpservicesetup.auth.md) | HttpAuth | Auth status. See [HttpAuth](./kibana-plugin-core-server.httpauth.md) | | [basePath](./kibana-plugin-core-server.httpservicesetup.basepath.md) | IBasePath | Access or manipulate the Kibana base path See [IBasePath](./kibana-plugin-core-server.ibasepath.md). | | [createCookieSessionStorageFactory](./kibana-plugin-core-server.httpservicesetup.createcookiesessionstoragefactory.md) | <T>(cookieOptions: SessionStorageCookieOptions<T>) => Promise<SessionStorageFactory<T>> | Creates cookie based session storage factory [SessionStorageFactory](./kibana-plugin-core-server.sessionstoragefactory.md) | -| [createRouter](./kibana-plugin-core-server.httpservicesetup.createrouter.md) | () => IRouter | Provides ability to declare a handler function for a particular path and HTTP request method. | +| [createRouter](./kibana-plugin-core-server.httpservicesetup.createrouter.md) | <Context extends RequestHandlerContext = RequestHandlerContext>() => IRouter<Context> | Provides ability to declare a handler function for a particular path and HTTP request method. | | [csp](./kibana-plugin-core-server.httpservicesetup.csp.md) | ICspConfig | The CSP config used for Kibana. | | [getServerInfo](./kibana-plugin-core-server.httpservicesetup.getserverinfo.md) | () => HttpServerInfo | Provides common [information](./kibana-plugin-core-server.httpserverinfo.md) about the running http server. | | [registerAuth](./kibana-plugin-core-server.httpservicesetup.registerauth.md) | (handler: AuthenticationHandler) => void | To define custom authentication and/or authorization mechanism for incoming requests. | @@ -92,5 +92,5 @@ async (context, request, response) => { | [registerOnPreAuth](./kibana-plugin-core-server.httpservicesetup.registeronpreauth.md) | (handler: OnPreAuthHandler) => void | To define custom logic to perform for incoming requests before the Auth interceptor performs a check that user has access to requested resources. | | [registerOnPreResponse](./kibana-plugin-core-server.httpservicesetup.registeronpreresponse.md) | (handler: OnPreResponseHandler) => void | To define custom logic to perform for the server response. | | [registerOnPreRouting](./kibana-plugin-core-server.httpservicesetup.registeronprerouting.md) | (handler: OnPreRoutingHandler) => void | To define custom logic to perform for incoming requests before server performs a route lookup. | -| [registerRouteHandlerContext](./kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md) | <T extends keyof RequestHandlerContext>(contextName: T, provider: RequestHandlerContextProvider<T>) => RequestHandlerContextContainer | Register a context provider for a route handler. | +| [registerRouteHandlerContext](./kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md) | <Context extends RequestHandlerContext, ContextName extends keyof Context>(contextName: ContextName, provider: RequestHandlerContextProvider<Context, ContextName>) => RequestHandlerContextContainer | Register a context provider for a route handler. | diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md index b0dc4d44f7559..df3f80580f6da 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md @@ -9,7 +9,7 @@ Register a context provider for a route handler. Signature: ```typescript -registerRouteHandlerContext: (contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; +registerRouteHandlerContext: (contextName: ContextName, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; ``` ## Example @@ -17,7 +17,10 @@ registerRouteHandlerContext: (contextName ```ts // my-plugin.ts - deps.http.registerRouteHandlerContext( + interface MyRequestHandlerContext extends RequestHandlerContext { + myApp: { search(id: string): Promise }; + } + deps.http.registerRouteHandlerContext( 'myApp', (context, req) => { async function search (id: string) { @@ -28,6 +31,8 @@ registerRouteHandlerContext: (contextName ); // my-route-handler.ts + import type { MyRequestHandlerContext } from './my-plugin.ts'; + const router = createRouter(); router.get({ path: '/', validate: false }, async (context, req, res) => { const response = await context.myApp.search(...); return res.ok(response); diff --git a/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.md b/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.md index 0c2cd7a69901f..3b390e3aaa117 100644 --- a/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.md +++ b/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.md @@ -9,7 +9,7 @@ An object that handles registration of context providers and configuring handler Signature: ```typescript -export interface IContextContainer> +export interface IContextContainer ``` ## Remarks diff --git a/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.registercontext.md b/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.registercontext.md index 0813d81e5a72b..7f531fa8ba0d2 100644 --- a/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.registercontext.md +++ b/docs/development/core/server/kibana-plugin-core-server.icontextcontainer.registercontext.md @@ -9,7 +9,7 @@ Register a new context provider. Signature: ```typescript -registerContext>(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; +registerContext(pluginOpaqueId: PluginOpaqueId, contextName: ContextName, provider: IContextProvider): this; ``` ## Parameters @@ -17,8 +17,8 @@ registerContext>(pluginO | Parameter | Type | Description | | --- | --- | --- | | pluginOpaqueId | PluginOpaqueId | The plugin opaque ID for the plugin that registers this context. | -| contextName | TContextName | The key of the TContext object this provider supplies the value for. | -| provider | IContextProvider<THandler, TContextName> | A [IContextProvider](./kibana-plugin-core-server.icontextprovider.md) to be called each time a new context is created. | +| contextName | ContextName | The key of the TContext object this provider supplies the value for. | +| provider | IContextProvider<Context, ContextName> | A [IContextProvider](./kibana-plugin-core-server.icontextprovider.md) to be called each time a new context is created. | Returns: diff --git a/docs/development/core/server/kibana-plugin-core-server.icontextprovider.md b/docs/development/core/server/kibana-plugin-core-server.icontextprovider.md index 7d124b266bcc1..ddd8a0e92f465 100644 --- a/docs/development/core/server/kibana-plugin-core-server.icontextprovider.md +++ b/docs/development/core/server/kibana-plugin-core-server.icontextprovider.md @@ -9,7 +9,7 @@ A function that returns a context value for a specific key of given context type Signature: ```typescript -export declare type IContextProvider, TContextName extends keyof HandlerContextType> = (context: PartialExceptFor, 'core'>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; +export declare type IContextProvider = (context: Omit, ...rest: HandlerParameters) => Promise | Context[ContextName]; ``` ## Remarks diff --git a/docs/development/core/server/kibana-plugin-core-server.irouter.delete.md b/docs/development/core/server/kibana-plugin-core-server.irouter.delete.md index d4c4692239d79..a7b6dd5bc294e 100644 --- a/docs/development/core/server/kibana-plugin-core-server.irouter.delete.md +++ b/docs/development/core/server/kibana-plugin-core-server.irouter.delete.md @@ -9,5 +9,5 @@ Register a route handler for `DELETE` request. Signature: ```typescript -delete: RouteRegistrar<'delete'>; +delete: RouteRegistrar<'delete', Context>; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.irouter.get.md b/docs/development/core/server/kibana-plugin-core-server.irouter.get.md index 38ed9ea96455e..7db694b38da47 100644 --- a/docs/development/core/server/kibana-plugin-core-server.irouter.get.md +++ b/docs/development/core/server/kibana-plugin-core-server.irouter.get.md @@ -9,5 +9,5 @@ Register a route handler for `GET` request. Signature: ```typescript -get: RouteRegistrar<'get'>; +get: RouteRegistrar<'get', Context>; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.irouter.md b/docs/development/core/server/kibana-plugin-core-server.irouter.md index 4bade638a65a5..a0a27e828f865 100644 --- a/docs/development/core/server/kibana-plugin-core-server.irouter.md +++ b/docs/development/core/server/kibana-plugin-core-server.irouter.md @@ -9,18 +9,18 @@ Registers route handlers for specified resource path and method. See [RouteConfi Signature: ```typescript -export interface IRouter +export interface IRouter ``` ## Properties | Property | Type | Description | | --- | --- | --- | -| [delete](./kibana-plugin-core-server.irouter.delete.md) | RouteRegistrar<'delete'> | Register a route handler for DELETE request. | -| [get](./kibana-plugin-core-server.irouter.get.md) | RouteRegistrar<'get'> | Register a route handler for GET request. | +| [delete](./kibana-plugin-core-server.irouter.delete.md) | RouteRegistrar<'delete', Context> | Register a route handler for DELETE request. | +| [get](./kibana-plugin-core-server.irouter.get.md) | RouteRegistrar<'get', Context> | Register a route handler for GET request. | | [handleLegacyErrors](./kibana-plugin-core-server.irouter.handlelegacyerrors.md) | RequestHandlerWrapper | Wrap a router handler to catch and converts legacy boom errors to proper custom errors. | -| [patch](./kibana-plugin-core-server.irouter.patch.md) | RouteRegistrar<'patch'> | Register a route handler for PATCH request. | -| [post](./kibana-plugin-core-server.irouter.post.md) | RouteRegistrar<'post'> | Register a route handler for POST request. | -| [put](./kibana-plugin-core-server.irouter.put.md) | RouteRegistrar<'put'> | Register a route handler for PUT request. | +| [patch](./kibana-plugin-core-server.irouter.patch.md) | RouteRegistrar<'patch', Context> | Register a route handler for PATCH request. | +| [post](./kibana-plugin-core-server.irouter.post.md) | RouteRegistrar<'post', Context> | Register a route handler for POST request. | +| [put](./kibana-plugin-core-server.irouter.put.md) | RouteRegistrar<'put', Context> | Register a route handler for PUT request. | | [routerPath](./kibana-plugin-core-server.irouter.routerpath.md) | string | Resulted path | diff --git a/docs/development/core/server/kibana-plugin-core-server.irouter.patch.md b/docs/development/core/server/kibana-plugin-core-server.irouter.patch.md index f835eb9800735..b353079630ecb 100644 --- a/docs/development/core/server/kibana-plugin-core-server.irouter.patch.md +++ b/docs/development/core/server/kibana-plugin-core-server.irouter.patch.md @@ -9,5 +9,5 @@ Register a route handler for `PATCH` request. Signature: ```typescript -patch: RouteRegistrar<'patch'>; +patch: RouteRegistrar<'patch', Context>; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.irouter.post.md b/docs/development/core/server/kibana-plugin-core-server.irouter.post.md index 312b83d570a42..94c703ad6f339 100644 --- a/docs/development/core/server/kibana-plugin-core-server.irouter.post.md +++ b/docs/development/core/server/kibana-plugin-core-server.irouter.post.md @@ -9,5 +9,5 @@ Register a route handler for `POST` request. Signature: ```typescript -post: RouteRegistrar<'post'>; +post: RouteRegistrar<'post', Context>; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.irouter.put.md b/docs/development/core/server/kibana-plugin-core-server.irouter.put.md index d8a8271b6fc9e..702ff3ff61bb6 100644 --- a/docs/development/core/server/kibana-plugin-core-server.irouter.put.md +++ b/docs/development/core/server/kibana-plugin-core-server.irouter.put.md @@ -9,5 +9,5 @@ Register a route handler for `PUT` request. Signature: ```typescript -put: RouteRegistrar<'put'>; +put: RouteRegistrar<'put', Context>; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.requesthandler.md b/docs/development/core/server/kibana-plugin-core-server.requesthandler.md index cecef7c923568..0032e52a0e906 100644 --- a/docs/development/core/server/kibana-plugin-core-server.requesthandler.md +++ b/docs/development/core/server/kibana-plugin-core-server.requesthandler.md @@ -9,7 +9,7 @@ A function executed when route path matched requested resource path. Request han Signature: ```typescript -export declare type RequestHandler

= (context: RequestHandlerContext, request: KibanaRequest, response: ResponseFactory) => IKibanaResponse | Promise>; +export declare type RequestHandler

= (context: Context, request: KibanaRequest, response: ResponseFactory) => IKibanaResponse | Promise>; ``` ## Example diff --git a/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextcontainer.md b/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextcontainer.md index c95a16670b190..6966deb9d7cc7 100644 --- a/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextcontainer.md +++ b/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextcontainer.md @@ -9,5 +9,5 @@ An object that handles registration of http request context providers. Signature: ```typescript -export declare type RequestHandlerContextContainer = IContextContainer>; +export declare type RequestHandlerContextContainer = IContextContainer; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextprovider.md b/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextprovider.md index cd30b3c1f43e3..d94facd849eff 100644 --- a/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextprovider.md +++ b/docs/development/core/server/kibana-plugin-core-server.requesthandlercontextprovider.md @@ -9,5 +9,5 @@ Context provider for request handler. Extends request context object with provid Signature: ```typescript -export declare type RequestHandlerContextProvider = IContextProvider, TContextName>; +export declare type RequestHandlerContextProvider = IContextProvider; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.requesthandlerwrapper.md b/docs/development/core/server/kibana-plugin-core-server.requesthandlerwrapper.md index a9fe188ee2bff..76c7ee4f22902 100644 --- a/docs/development/core/server/kibana-plugin-core-server.requesthandlerwrapper.md +++ b/docs/development/core/server/kibana-plugin-core-server.requesthandlerwrapper.md @@ -9,7 +9,7 @@ Type-safe wrapper for [RequestHandler](./kibana-plugin-core-server.requesthandle Signature: ```typescript -export declare type RequestHandlerWrapper = (handler: RequestHandler) => RequestHandler; +export declare type RequestHandlerWrapper = (handler: RequestHandler) => RequestHandler; ``` ## Example diff --git a/docs/development/core/server/kibana-plugin-core-server.routeregistrar.md b/docs/development/core/server/kibana-plugin-core-server.routeregistrar.md index 121a8eee1bfcd..3ddb350a38b6f 100644 --- a/docs/development/core/server/kibana-plugin-core-server.routeregistrar.md +++ b/docs/development/core/server/kibana-plugin-core-server.routeregistrar.md @@ -9,5 +9,5 @@ Route handler common definition Signature: ```typescript -export declare type RouteRegistrar = (route: RouteConfig, handler: RequestHandler) => void; +export declare type RouteRegistrar = (route: RouteConfig, handler: RequestHandler) => void; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md index 3bc2a20541777..496e1ae9677d8 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md @@ -15,13 +15,13 @@ Using `createSearchSource`, the instance can be re-created. ```typescript serialize(): { searchSourceJSON: string; - references: import("src/core/server").SavedObjectReference[]; + references: import("../../../../../core/types").SavedObjectReference[]; }; ``` Returns: `{ searchSourceJSON: string; - references: import("src/core/server").SavedObjectReference[]; + references: import("../../../../../core/types").SavedObjectReference[]; }` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.dataapirequesthandlercontext.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.dataapirequesthandlercontext.md new file mode 100644 index 0000000000000..8b7b025d80181 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.dataapirequesthandlercontext.md @@ -0,0 +1,18 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [DataApiRequestHandlerContext](./kibana-plugin-plugins-data-server.dataapirequesthandlercontext.md) + +## DataApiRequestHandlerContext interface + +Signature: + +```typescript +export interface DataApiRequestHandlerContext extends ISearchClient +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [session](./kibana-plugin-plugins-data-server.dataapirequesthandlercontext.session.md) | IScopedSessionService | | + diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.dataapirequesthandlercontext.session.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.dataapirequesthandlercontext.session.md new file mode 100644 index 0000000000000..9a6e3f55d3929 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.dataapirequesthandlercontext.session.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [DataApiRequestHandlerContext](./kibana-plugin-plugins-data-server.dataapirequesthandlercontext.md) > [session](./kibana-plugin-plugins-data-server.dataapirequesthandlercontext.session.md) + +## DataApiRequestHandlerContext.session property + +Signature: + +```typescript +session: IScopedSessionService; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md index e6cb5accb9e31..84c7875c26ce8 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md @@ -45,6 +45,7 @@ | --- | --- | | [AggFunctionsMapping](./kibana-plugin-plugins-data-server.aggfunctionsmapping.md) | A global list of the expression function definitions for each agg type function. | | [AggParamOption](./kibana-plugin-plugins-data-server.aggparamoption.md) | | +| [DataApiRequestHandlerContext](./kibana-plugin-plugins-data-server.dataapirequesthandlercontext.md) | | | [EsQueryConfig](./kibana-plugin-plugins-data-server.esqueryconfig.md) | | | [FieldDescriptor](./kibana-plugin-plugins-data-server.fielddescriptor.md) | | | [FieldFormatConfig](./kibana-plugin-plugins-data-server.fieldformatconfig.md) | | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.plugin.start.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.plugin.start.md index 8f1ea7b95a5f9..af7abb076d7ef 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.plugin.start.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.plugin.start.md @@ -9,10 +9,10 @@ ```typescript start(core: CoreStart): { fieldFormats: { - fieldFormatServiceFactory: (uiSettings: import("src/core/server").IUiSettingsClient) => Promise; + fieldFormatServiceFactory: (uiSettings: import("../../../core/server").IUiSettingsClient) => Promise; }; indexPatterns: { - indexPatternsServiceFactory: (savedObjectsClient: Pick, elasticsearchClient: import("src/core/server").ElasticsearchClient) => Promise; + indexPatternsServiceFactory: (savedObjectsClient: Pick, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise; }; search: ISearchStart>; }; @@ -28,10 +28,10 @@ start(core: CoreStart): { `{ fieldFormats: { - fieldFormatServiceFactory: (uiSettings: import("src/core/server").IUiSettingsClient) => Promise; + fieldFormatServiceFactory: (uiSettings: import("../../../core/server").IUiSettingsClient) => Promise; }; indexPatterns: { - indexPatternsServiceFactory: (savedObjectsClient: Pick, elasticsearchClient: import("src/core/server").ElasticsearchClient) => Promise; + indexPatternsServiceFactory: (savedObjectsClient: Pick, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise; }; search: ISearchStart>; }` diff --git a/examples/search_examples/server/plugin.ts b/examples/search_examples/server/plugin.ts index 605d4b0ec8291..e7ee311c8d652 100644 --- a/examples/search_examples/server/plugin.ts +++ b/examples/search_examples/server/plugin.ts @@ -6,13 +6,16 @@ * Public License, v 1. */ -import { +import type { PluginInitializerContext, CoreSetup, CoreStart, Plugin, Logger, -} from '../../../src/core/server'; + RequestHandlerContext, +} from 'src/core/server'; + +import type { DataApiRequestHandlerContext } from 'src/plugins/data/server'; import { SearchExamplesPluginSetup, @@ -42,12 +45,14 @@ export class SearchExamplesPlugin deps: SearchExamplesPluginSetupDeps ) { this.logger.debug('search_examples: Setup'); - const router = core.http.createRouter(); + const router = core.http.createRouter< + RequestHandlerContext & { search: DataApiRequestHandlerContext } + >(); core.getStartServices().then(([_, depsStart]) => { const myStrategy = mySearchStrategyProvider(depsStart.data); deps.data.search.registerSearchStrategy('myStrategy', myStrategy); - registerRoutes(router, depsStart.data); + registerRoutes(router); }); return {}; diff --git a/examples/search_examples/server/routes/register_routes.ts b/examples/search_examples/server/routes/register_routes.ts index 87d2e96137736..d7a18509b9a79 100644 --- a/examples/search_examples/server/routes/register_routes.ts +++ b/examples/search_examples/server/routes/register_routes.ts @@ -6,10 +6,12 @@ * Public License, v 1. */ -import { IRouter } from 'kibana/server'; -import { PluginStart as DataPluginStart } from 'src/plugins/data/server'; +import type { IRouter, RequestHandlerContext } from 'kibana/server'; +import { DataApiRequestHandlerContext } from 'src/plugins/data/server'; import { registerServerSearchRoute } from './server_search_route'; -export function registerRoutes(router: IRouter, data: DataPluginStart) { - registerServerSearchRoute(router, data); +export function registerRoutes( + router: IRouter +) { + registerServerSearchRoute(router); } diff --git a/examples/search_examples/server/routes/server_search_route.ts b/examples/search_examples/server/routes/server_search_route.ts index c16ba55b8abec..99a1aba99d8ec 100644 --- a/examples/search_examples/server/routes/server_search_route.ts +++ b/examples/search_examples/server/routes/server_search_route.ts @@ -6,13 +6,16 @@ * Public License, v 1. */ -import { PluginStart as DataPluginStart, IEsSearchRequest } from 'src/plugins/data/server'; +import { IEsSearchRequest } from 'src/plugins/data/server'; import { schema } from '@kbn/config-schema'; import { IEsSearchResponse } from 'src/plugins/data/common'; -import { IRouter } from '../../../../src/core/server'; +import type { DataApiRequestHandlerContext } from 'src/plugins/data/server'; +import type { IRouter, RequestHandlerContext } from 'src/core/server'; import { SERVER_SEARCH_ROUTE_PATH } from '../../common'; -export function registerServerSearchRoute(router: IRouter, data: DataPluginStart) { +export function registerServerSearchRoute( + router: IRouter +) { router.get( { path: SERVER_SEARCH_ROUTE_PATH, diff --git a/src/core/utils/context.mock.ts b/src/core/server/context/container/context.mock.ts similarity index 92% rename from src/core/utils/context.mock.ts rename to src/core/server/context/container/context.mock.ts index fe15cbc7681d5..7f5a8ef28aab1 100644 --- a/src/core/utils/context.mock.ts +++ b/src/core/server/context/container/context.mock.ts @@ -12,6 +12,7 @@ export type ContextContainerMock = jest.Mocked>; const createContextMock = (mockContext = {}) => { const contextMock: ContextContainerMock = { + // @ts-expect-error tsc cannot infer ContextName and uses never registerContext: jest.fn(), createHandler: jest.fn(), }; diff --git a/src/core/server/context/container/context.test.ts b/src/core/server/context/container/context.test.ts new file mode 100644 index 0000000000000..0e697d64ed2ec --- /dev/null +++ b/src/core/server/context/container/context.test.ts @@ -0,0 +1,319 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * and the Server Side Public License, v 1; you may not use this file except in + * compliance with, at your election, the Elastic License or the Server Side + * Public License, v 1. + */ + +import { ContextContainer } from './context'; +import { PluginOpaqueId } from '../..'; +import { httpServerMock } from '../../http/http_server.mocks'; + +const pluginA = Symbol('pluginA'); +const pluginB = Symbol('pluginB'); +const pluginC = Symbol('pluginC'); +const pluginD = Symbol('pluginD'); +const plugins: ReadonlyMap = new Map([ + [pluginA, []], + [pluginB, [pluginA]], + [pluginC, [pluginA, pluginB]], + [pluginD, []], +]); +const coreId = Symbol(); + +interface MyContext { + core: any; + core1: string; + core2: number; + ctxFromA: string; + ctxFromB: number; + ctxFromC: boolean; + ctxFromD: object; +} + +describe('ContextContainer', () => { + it('does not allow the same context to be registered twice', () => { + const contextContainer = new ContextContainer(plugins, coreId); + contextContainer.registerContext<{ ctxFromA: string; core: any }, 'ctxFromA'>( + coreId, + 'ctxFromA', + () => 'aString' + ); + + expect(() => + contextContainer.registerContext<{ ctxFromA: string; core: any }, 'ctxFromA'>( + coreId, + 'ctxFromA', + () => 'aString' + ) + ).toThrowErrorMatchingInlineSnapshot( + `"Context provider for ctxFromA has already been registered."` + ); + }); + + describe('registerContext', () => { + it('throws error if called with an unknown symbol', async () => { + const contextContainer = new ContextContainer(plugins, coreId); + await expect(() => + contextContainer.registerContext<{ ctxFromA: string; core: any }, 'ctxFromA'>( + Symbol('unknown'), + 'ctxFromA', + jest.fn() + ) + ).toThrowErrorMatchingInlineSnapshot( + `"Cannot register context for unknown plugin: Symbol(unknown)"` + ); + }); + }); + + describe('context building', () => { + it('resolves dependencies', async () => { + const contextContainer = new ContextContainer(plugins, coreId); + expect.assertions(8); + contextContainer.registerContext<{ core1: string; core: any }, 'core1'>( + coreId, + 'core1', + (context) => { + expect(context).toEqual({}); + return 'core'; + } + ); + + contextContainer.registerContext<{ ctxFromA: string; core: any }, 'ctxFromA'>( + pluginA, + 'ctxFromA', + (context) => { + expect(context).toEqual({ core1: 'core' }); + return 'aString'; + } + ); + contextContainer.registerContext<{ ctxFromB: number; core: any }, 'ctxFromB'>( + pluginB, + 'ctxFromB', + (context) => { + expect(context).toEqual({ core1: 'core', ctxFromA: 'aString' }); + return 299; + } + ); + contextContainer.registerContext<{ ctxFromC: boolean; core: any }, 'ctxFromC'>( + pluginC, + 'ctxFromC', + (context) => { + expect(context).toEqual({ + core1: 'core', + ctxFromA: 'aString', + ctxFromB: 299, + }); + return false; + } + ); + contextContainer.registerContext<{ ctxFromD: {}; core: any }, 'ctxFromD'>( + pluginD, + 'ctxFromD', + (context) => { + expect(context).toEqual({ core1: 'core' }); + return {}; + } + ); + + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(pluginC, rawHandler1); + + const rawHandler2 = jest.fn(() => 'handler2' as any); + const handler2 = contextContainer.createHandler(pluginD, rawHandler2); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + + await handler1(request, response); + await handler2(request, response); + + // Should have context from pluginC, its deps, and core + expect(rawHandler1).toHaveBeenCalledWith( + { + core1: 'core', + ctxFromA: 'aString', + ctxFromB: 299, + ctxFromC: false, + }, + request, + response + ); + + // Should have context from pluginD, and core + expect(rawHandler2).toHaveBeenCalledWith( + { + core1: 'core', + ctxFromD: {}, + }, + request, + response + ); + }); + + it('exposes all core context to all providers regardless of registration order', async () => { + expect.assertions(4); + + const contextContainer = new ContextContainer(plugins, coreId); + contextContainer + .registerContext(pluginA, 'ctxFromA', (context) => { + expect(context).toEqual({ core1: 'core', core2: 101 }); + return `aString ${context.core1} ${context.core2}`; + }) + .registerContext(coreId, 'core1', () => 'core') + .registerContext(coreId, 'core2', () => 101) + .registerContext(pluginB, 'ctxFromB', (context) => { + expect(context).toEqual({ + core1: 'core', + core2: 101, + ctxFromA: 'aString core 101', + }); + return 277; + }); + + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(pluginB, rawHandler1); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + expect(await handler1(request, response)).toEqual('handler1'); + + expect(rawHandler1).toHaveBeenCalledWith( + { + core1: 'core', + core2: 101, + ctxFromA: 'aString core 101', + ctxFromB: 277, + }, + request, + response + ); + }); + + it('exposes all core context to core providers', async () => { + expect.assertions(4); + const contextContainer = new ContextContainer(plugins, coreId); + + contextContainer + .registerContext(coreId, 'core1', (context) => { + expect(context).toEqual({}); + return 'core'; + }) + .registerContext(coreId, 'core2', (context) => { + expect(context).toEqual({ core1: 'core' }); + return 101; + }); + + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(pluginA, rawHandler1); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + expect(await handler1(request, response)).toEqual('handler1'); + + // If no context is registered for pluginA, only core contexts should be exposed + expect(rawHandler1).toHaveBeenCalledWith( + { + core1: 'core', + core2: 101, + }, + request, + response + ); + }); + + it('does not expose plugin contexts to core handler', async () => { + const contextContainer = new ContextContainer(plugins, coreId); + + contextContainer + .registerContext(coreId, 'core1', (context) => 'core') + .registerContext(pluginA, 'ctxFromA', (context) => 'aString'); + + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(coreId, rawHandler1); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + expect(await handler1(request, response)).toEqual('handler1'); + // pluginA context should not be present in a core handler + expect(rawHandler1).toHaveBeenCalledWith( + { + core1: 'core', + }, + request, + response + ); + }); + + it('passes additional arguments to providers', async () => { + expect.assertions(6); + const contextContainer = new ContextContainer(plugins, coreId); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + contextContainer.registerContext(coreId, 'core1', (context, req, res) => { + expect(req).toBe(request); + expect(res).toBe(response); + return 'core'; + }); + + contextContainer.registerContext( + pluginD, + 'ctxFromB', + (context, req, res) => { + expect(req).toBe(request); + expect(res).toBe(response); + return 77; + } + ); + + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(pluginD, rawHandler1); + + expect(await handler1(request, response)).toEqual('handler1'); + + expect(rawHandler1).toHaveBeenCalledWith( + { + core1: 'core', + ctxFromB: 77, + }, + request, + response + ); + }); + }); + + describe('createHandler', () => { + it('throws error if called with an unknown symbol', async () => { + const contextContainer = new ContextContainer(plugins, coreId); + await expect(() => + contextContainer.createHandler(Symbol('unknown'), jest.fn()) + ).toThrowErrorMatchingInlineSnapshot( + `"Cannot create handler for unknown plugin: Symbol(unknown)"` + ); + }); + + it('returns value from original handler', async () => { + const contextContainer = new ContextContainer(plugins, coreId); + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(pluginA, rawHandler1); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + expect(await handler1(request, response)).toEqual('handler1'); + }); + + it('passes additional arguments to handlers', async () => { + const contextContainer = new ContextContainer(plugins, coreId); + + const rawHandler1 = jest.fn(() => 'handler1' as any); + const handler1 = contextContainer.createHandler(pluginA, rawHandler1); + + const request = httpServerMock.createKibanaRequest(); + const response = httpServerMock.createResponseFactory(); + await handler1(request, response); + expect(rawHandler1).toHaveBeenCalledWith({}, request, response); + }); + }); +}); diff --git a/src/core/utils/context.ts b/src/core/server/context/container/context.ts similarity index 85% rename from src/core/utils/context.ts rename to src/core/server/context/container/context.ts index f3d4370013827..234fb7d34700d 100644 --- a/src/core/utils/context.ts +++ b/src/core/server/context/container/context.ts @@ -8,13 +8,8 @@ import { flatten } from 'lodash'; import { ShallowPromise } from '@kbn/utility-types'; -import { pick } from '@kbn/std'; -import type { CoreId, PluginOpaqueId } from '../server'; - -/** - * Make all properties in T optional, except for the properties whose keys are in the union K - */ -type PartialExceptFor = Partial & Pick; +import { pick } from 'lodash'; +import type { CoreId, PluginOpaqueId, RequestHandler, RequestHandlerContext } from '../..'; /** * A function that returns a context value for a specific key of given context type. @@ -30,15 +25,13 @@ type PartialExceptFor = Partial & Pick; * @public */ export type IContextProvider< - THandler extends HandlerFunction, - TContextName extends keyof HandlerContextType + Context extends RequestHandlerContext, + ContextName extends keyof Context > = ( // context.core will always be available, but plugin contexts are typed as optional - context: PartialExceptFor, 'core'>, - ...rest: HandlerParameters -) => - | Promise[TContextName]> - | HandlerContextType[TContextName]; + context: Omit, + ...rest: HandlerParameters +) => Promise | Context[ContextName]; /** * A function that accepts a context object and an optional number of additional arguments. Used for the generic types @@ -142,7 +135,7 @@ export type HandlerParameters> = T extends ( * * @public */ -export interface IContextContainer> { +export interface IContextContainer { /** * Register a new context provider. * @@ -157,10 +150,10 @@ export interface IContextContainer> { * @param provider - A {@link IContextProvider} to be called each time a new context is created. * @returns The {@link IContextContainer} for method chaining. */ - registerContext>( + registerContext( pluginOpaqueId: PluginOpaqueId, - contextName: TContextName, - provider: IContextProvider + contextName: ContextName, + provider: IContextProvider ): this; /** @@ -178,21 +171,21 @@ export interface IContextContainer> { } /** @internal */ -export class ContextContainer> +export class ContextContainer implements IContextContainer { /** * Used to map contexts to their providers and associated plugin. In registration order which is tightly coupled to * plugin load order. */ private readonly contextProviders = new Map< - keyof HandlerContextType, + string, { - provider: IContextProvider>; + provider: IContextProvider; source: symbol; } >(); /** Used to keep track of which plugins registered which contexts for dependency resolution. */ - private readonly contextNamesBySource: Map>>; + private readonly contextNamesBySource: Map; /** * @param pluginDependencies - A map of plugins to an array of their dependencies. @@ -201,16 +194,18 @@ export class ContextContainer> private readonly pluginDependencies: ReadonlyMap, private readonly coreId: CoreId ) { - this.contextNamesBySource = new Map>>([ - [coreId, []], - ]); + this.contextNamesBySource = new Map([[coreId, []]]); } - public registerContext = >( + public registerContext = < + Context extends RequestHandlerContext, + ContextName extends keyof Context + >( source: symbol, - contextName: TContextName, - provider: IContextProvider + name: ContextName, + provider: IContextProvider ): this => { + const contextName = name as string; if (this.contextProviders.has(contextName)) { throw new Error(`Context provider for ${contextName} has already been registered.`); } @@ -234,6 +229,7 @@ export class ContextContainer> return (async (...args: HandlerParameters) => { const context = await this.buildContext(source, ...args); + // @ts-expect-error requires explicit handler arity return handler(context, ...args); }) as (...args: HandlerParameters) => ShallowPromise>; }; @@ -242,9 +238,7 @@ export class ContextContainer> source: symbol, ...contextArgs: HandlerParameters ): Promise> { - const contextsToBuild: ReadonlySet> = new Set( - this.getContextNamesForSource(source) - ); + const contextsToBuild = new Set(this.getContextNamesForSource(source)); return [...this.contextProviders] .sort(sortByCoreFirst(this.coreId)) @@ -256,18 +250,17 @@ export class ContextContainer> // registered that provider. const exposedContext = pick(resolvedContext, [ ...this.getContextNamesForSource(providerSource), - ]) as PartialExceptFor, 'core'>; + ]); return { ...resolvedContext, + // @ts-expect-error requires explicit provider arity [contextName]: await provider(exposedContext, ...contextArgs), }; }, Promise.resolve({}) as Promise>); } - private getContextNamesForSource( - source: symbol - ): ReadonlySet> { + private getContextNamesForSource(source: symbol): ReadonlySet { if (source === this.coreId) { return this.getContextNamesForCore(); } else { diff --git a/src/core/server/context/container/index.ts b/src/core/server/context/container/index.ts new file mode 100644 index 0000000000000..b553c1b65223c --- /dev/null +++ b/src/core/server/context/container/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * and the Server Side Public License, v 1; you may not use this file except in + * compliance with, at your election, the Elastic License or the Server Side + * Public License, v 1. + */ + +export * from './context'; diff --git a/src/core/server/context/context_service.mock.ts b/src/core/server/context/context_service.mock.ts index 1ce1b26e3a4dc..c849c0b6b6974 100644 --- a/src/core/server/context/context_service.mock.ts +++ b/src/core/server/context/context_service.mock.ts @@ -9,7 +9,7 @@ import type { PublicMethodsOf } from '@kbn/utility-types'; import { ContextService, ContextSetup } from './context_service'; -import { contextMock } from '../../utils/context.mock'; +import { contextMock } from './container/context.mock'; const createSetupContractMock = (mockContext = {}) => { const setupContract: jest.Mocked = { diff --git a/src/core/server/context/context_service.test.mocks.ts b/src/core/server/context/context_service.test.mocks.ts index 2b6fedb15c8c5..7a69afb002c35 100644 --- a/src/core/server/context/context_service.test.mocks.ts +++ b/src/core/server/context/context_service.test.mocks.ts @@ -6,9 +6,9 @@ * Public License, v 1. */ -import { contextMock } from '../../utils/context.mock'; +import { contextMock } from './container/context.mock'; export const MockContextConstructor = jest.fn(contextMock.create); -jest.doMock('../../utils/context', () => ({ +jest.doMock('./container/context', () => ({ ContextContainer: MockContextConstructor, })); diff --git a/src/core/server/context/context_service.ts b/src/core/server/context/context_service.ts index 7a9ee4e3d35c2..1f4bd7c2e3af2 100644 --- a/src/core/server/context/context_service.ts +++ b/src/core/server/context/context_service.ts @@ -7,7 +7,7 @@ */ import { PluginOpaqueId } from '../../server'; -import { IContextContainer, ContextContainer, HandlerFunction } from '../../utils/context'; +import { IContextContainer, ContextContainer, HandlerFunction } from './container'; import { CoreContext } from '../core_context'; interface SetupDeps { diff --git a/src/core/server/context/index.ts b/src/core/server/context/index.ts index b9a8e0d7f498f..8c690034368d9 100644 --- a/src/core/server/context/index.ts +++ b/src/core/server/context/index.ts @@ -13,4 +13,4 @@ export { HandlerFunction, HandlerContextType, HandlerParameters, -} from '../../utils/context'; +} from './container'; diff --git a/src/core/server/http/http_service.mock.ts b/src/core/server/http/http_service.mock.ts index eb90783bb4647..f9d6ef3cb38d1 100644 --- a/src/core/server/http/http_service.mock.ts +++ b/src/core/server/http/http_service.mock.ts @@ -89,6 +89,7 @@ const createInternalSetupContractMock = () => { registerOnPreAuth: jest.fn(), registerAuth: jest.fn(), registerOnPostAuth: jest.fn(), + // @ts-expect-error tsc cannot infer ContextName and uses never registerRouteHandlerContext: jest.fn(), registerOnPreResponse: jest.fn(), createRouter: jest.fn().mockImplementation(() => mockRouter.create({})), @@ -125,6 +126,7 @@ const createSetupContractMock = () => { basePath: internalMock.basePath, csp: CspConfig.DEFAULT, createRouter: jest.fn(), + // @ts-expect-error tsc cannot infer ContextName and uses never registerRouteHandlerContext: jest.fn(), auth: { get: internalMock.auth.get, diff --git a/src/core/server/http/http_service.ts b/src/core/server/http/http_service.ts index 0a3dfa12e1df5..0e4ab8ec4cd66 100644 --- a/src/core/server/http/http_service.ts +++ b/src/core/server/http/http_service.ts @@ -11,6 +11,7 @@ import { first, map } from 'rxjs/operators'; import { Server } from '@hapi/hapi'; import { pick } from '@kbn/std'; +import type { RequestHandlerContext } from 'src/core/server'; import { CoreService } from '../../types'; import { Logger, LoggerFactory } from '../logging'; import { ContextSetup } from '../context'; @@ -31,7 +32,6 @@ import { InternalHttpServiceStart, } from './types'; -import { RequestHandlerContext } from '../../server'; import { registerCoreHandlers } from './lifecycle_handlers'; import { ExternalUrlConfigType, @@ -100,17 +100,23 @@ export class HttpService externalUrl: new ExternalUrlConfig(config.externalUrl), - createRouter: (path: string, pluginId: PluginOpaqueId = this.coreContext.coreId) => { + createRouter: ( + path: string, + pluginId: PluginOpaqueId = this.coreContext.coreId + ) => { const enhanceHandler = this.requestHandlerContext!.createHandler.bind(null, pluginId); - const router = new Router(path, this.log, enhanceHandler); + const router = new Router(path, this.log, enhanceHandler); registerRouter(router); return router; }, - registerRouteHandlerContext: ( + registerRouteHandlerContext: < + Context extends RequestHandlerContext, + ContextName extends keyof Context + >( pluginOpaqueId: PluginOpaqueId, - contextName: T, - provider: RequestHandlerContextProvider + contextName: ContextName, + provider: RequestHandlerContextProvider ) => this.requestHandlerContext!.registerContext(pluginOpaqueId, contextName, provider), }; diff --git a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts index 3fdc452101576..349758d9c3912 100644 --- a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts +++ b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts @@ -175,19 +175,19 @@ describe('core lifecycle handlers', () => { }); destructiveMethods.forEach((method) => { - ((router as any)[method.toLowerCase()] as RouteRegistrar)( + ((router as any)[method.toLowerCase()] as RouteRegistrar)( { path: testPath, validate: false }, (context, req, res) => { return res.ok({ body: 'ok' }); } ); - ((router as any)[method.toLowerCase()] as RouteRegistrar)( + ((router as any)[method.toLowerCase()] as RouteRegistrar)( { path: allowlistedTestPath, validate: false }, (context, req, res) => { return res.ok({ body: 'ok' }); } ); - ((router as any)[method.toLowerCase()] as RouteRegistrar)( + ((router as any)[method.toLowerCase()] as RouteRegistrar)( { path: xsrfDisabledTestPath, validate: false, options: { xsrfRequired: false } }, (context, req, res) => { return res.ok({ body: 'ok' }); diff --git a/src/core/server/http/router/router.mock.ts b/src/core/server/http/router/router.mock.ts index ee515a3ffddf8..b3ff8ce983abf 100644 --- a/src/core/server/http/router/router.mock.ts +++ b/src/core/server/http/router/router.mock.ts @@ -8,7 +8,7 @@ import { IRouter } from './router'; -export type RouterMock = jest.Mocked; +export type RouterMock = jest.Mocked>; function create({ routerPath = '' }: { routerPath?: string } = {}): RouterMock { return { diff --git a/src/core/server/http/router/router.ts b/src/core/server/http/router/router.ts index 4a5db793b0b0f..1368714aa993f 100644 --- a/src/core/server/http/router/router.ts +++ b/src/core/server/http/router/router.ts @@ -44,9 +44,12 @@ interface RouterRoute { * * @public */ -export type RouteRegistrar = ( +export type RouteRegistrar< + Method extends RouteMethod, + Context extends RequestHandlerContext = RequestHandlerContext +> = ( route: RouteConfig, - handler: RequestHandler + handler: RequestHandler ) => void; /** @@ -55,7 +58,7 @@ export type RouteRegistrar = ( * * @public */ -export interface IRouter { +export interface IRouter { /** * Resulted path */ @@ -66,35 +69,35 @@ export interface IRouter { * @param route {@link RouteConfig} - a route configuration. * @param handler {@link RequestHandler} - a function to call to respond to an incoming request */ - get: RouteRegistrar<'get'>; + get: RouteRegistrar<'get', Context>; /** * Register a route handler for `POST` request. * @param route {@link RouteConfig} - a route configuration. * @param handler {@link RequestHandler} - a function to call to respond to an incoming request */ - post: RouteRegistrar<'post'>; + post: RouteRegistrar<'post', Context>; /** * Register a route handler for `PUT` request. * @param route {@link RouteConfig} - a route configuration. * @param handler {@link RequestHandler} - a function to call to respond to an incoming request */ - put: RouteRegistrar<'put'>; + put: RouteRegistrar<'put', Context>; /** * Register a route handler for `PATCH` request. * @param route {@link RouteConfig} - a route configuration. * @param handler {@link RequestHandler} - a function to call to respond to an incoming request */ - patch: RouteRegistrar<'patch'>; + patch: RouteRegistrar<'patch', Context>; /** * Register a route handler for `DELETE` request. * @param route {@link RouteConfig} - a route configuration. * @param handler {@link RequestHandler} - a function to call to respond to an incoming request */ - delete: RouteRegistrar<'delete'>; + delete: RouteRegistrar<'delete', Context>; /** * Wrap a router handler to catch and converts legacy boom errors to proper custom errors. @@ -110,9 +113,13 @@ export interface IRouter { getRoutes: () => RouterRoute[]; } -export type ContextEnhancer = ( - handler: RequestHandler -) => RequestHandlerEnhanced; +export type ContextEnhancer< + P, + Q, + B, + Method extends RouteMethod, + Context extends RequestHandlerContext +> = (handler: RequestHandler) => RequestHandlerEnhanced; function getRouteFullPath(routerPath: string, routePath: string) { // If router's path ends with slash and route's path starts with slash, @@ -195,22 +202,23 @@ function validOptions( /** * @internal */ -export class Router implements IRouter { +export class Router + implements IRouter { public routes: Array> = []; - public get: IRouter['get']; - public post: IRouter['post']; - public delete: IRouter['delete']; - public put: IRouter['put']; - public patch: IRouter['patch']; + public get: IRouter['get']; + public post: IRouter['post']; + public delete: IRouter['delete']; + public put: IRouter['put']; + public patch: IRouter['patch']; constructor( public readonly routerPath: string, private readonly log: Logger, - private readonly enhanceWithContext: ContextEnhancer + private readonly enhanceWithContext: ContextEnhancer ) { const buildMethod = (method: Method) => ( route: RouteConfig, - handler: RequestHandler + handler: RequestHandler ) => { const routeSchemas = routeSchemasFromRouteConfig(route, method); @@ -300,7 +308,7 @@ type WithoutHeadArgument = T extends (first: any, ...rest: infer Params) => i : never; type RequestHandlerEnhanced = WithoutHeadArgument< - RequestHandler + RequestHandler >; /** @@ -341,10 +349,11 @@ export type RequestHandler< P = unknown, Q = unknown, B = unknown, + Context extends RequestHandlerContext = RequestHandlerContext, Method extends RouteMethod = any, ResponseFactory extends KibanaResponseFactory = KibanaResponseFactory > = ( - context: RequestHandlerContext, + context: Context, request: KibanaRequest, response: ResponseFactory ) => IKibanaResponse | Promise>; @@ -366,8 +375,9 @@ export type RequestHandlerWrapper = < P, Q, B, + Context extends RequestHandlerContext = RequestHandlerContext, Method extends RouteMethod = any, ResponseFactory extends KibanaResponseFactory = KibanaResponseFactory >( - handler: RequestHandler -) => RequestHandler; + handler: RequestHandler +) => RequestHandler; diff --git a/src/core/server/http/types.ts b/src/core/server/http/types.ts index fdcc7a87082ae..262ac3eb49f93 100644 --- a/src/core/server/http/types.ts +++ b/src/core/server/http/types.ts @@ -21,13 +21,13 @@ import { OnPostAuthHandler } from './lifecycle/on_post_auth'; import { OnPreResponseHandler } from './lifecycle/on_pre_response'; import { IBasePath } from './base_path_service'; import { ExternalUrlConfig } from '../external_url'; -import { PluginOpaqueId, RequestHandlerContext } from '..'; +import type { PluginOpaqueId, RequestHandlerContext } from '..'; /** * An object that handles registration of http request context providers. * @public */ -export type RequestHandlerContextContainer = IContextContainer>; +export type RequestHandlerContextContainer = IContextContainer; /** * Context provider for request handler. @@ -36,8 +36,9 @@ export type RequestHandlerContextContainer = IContextContainer = IContextProvider, TContextName>; + Context extends RequestHandlerContext, + ContextName extends keyof Context +> = IContextProvider; /** * @public @@ -230,14 +231,19 @@ export interface HttpServiceSetup { * ``` * @public */ - createRouter: () => IRouter; + createRouter: < + Context extends RequestHandlerContext = RequestHandlerContext + >() => IRouter; /** * Register a context provider for a route handler. * @example * ```ts * // my-plugin.ts - * deps.http.registerRouteHandlerContext( + * interface MyRequestHandlerContext extends RequestHandlerContext { + * myApp: { search(id: string): Promise }; + * } + * deps.http.registerRouteHandlerContext( * 'myApp', * (context, req) => { * async function search (id: string) { @@ -248,6 +254,8 @@ export interface HttpServiceSetup { * ); * * // my-route-handler.ts + * import type { MyRequestHandlerContext } from './my-plugin.ts'; + * const router = createRouter(); * router.get({ path: '/', validate: false }, async (context, req, res) => { * const response = await context.myApp.search(...); * return res.ok(response); @@ -255,9 +263,12 @@ export interface HttpServiceSetup { * ``` * @public */ - registerRouteHandlerContext: ( - contextName: T, - provider: RequestHandlerContextProvider + registerRouteHandlerContext: < + Context extends RequestHandlerContext, + ContextName extends keyof Context + >( + contextName: ContextName, + provider: RequestHandlerContextProvider ) => RequestHandlerContextContainer; /** @@ -272,13 +283,19 @@ export interface InternalHttpServiceSetup auth: HttpServerSetup['auth']; server: HttpServerSetup['server']; externalUrl: ExternalUrlConfig; - createRouter: (path: string, plugin?: PluginOpaqueId) => IRouter; + createRouter: ( + path: string, + plugin?: PluginOpaqueId + ) => IRouter; registerStaticDir: (path: string, dirPath: string) => void; getAuthHeaders: GetAuthHeaders; - registerRouteHandlerContext: ( + registerRouteHandlerContext: < + Context extends RequestHandlerContext, + ContextName extends keyof Context + >( pluginOpaqueId: PluginOpaqueId, - contextName: T, - provider: RequestHandlerContextProvider + contextName: ContextName, + provider: RequestHandlerContextProvider ) => RequestHandlerContextContainer; } diff --git a/src/core/server/http_resources/http_resources_service.ts b/src/core/server/http_resources/http_resources_service.ts index b8e4580164424..916fef2624381 100644 --- a/src/core/server/http_resources/http_resources_service.ts +++ b/src/core/server/http_resources/http_resources_service.ts @@ -53,12 +53,12 @@ export class HttpResourcesService implements CoreService( + register: ( route: RouteConfig, - handler: HttpResourcesRequestHandler + handler: HttpResourcesRequestHandler ) => { return router.get(route, (context, request, response) => { - return handler(context, request, { + return handler(context as Context, request, { ...response, ...this.createResponseToolkit(deps, context, request, response), }); diff --git a/src/core/server/http_resources/types.ts b/src/core/server/http_resources/types.ts index 6b1374d2d0be7..152bdd18f0211 100644 --- a/src/core/server/http_resources/types.ts +++ b/src/core/server/http_resources/types.ts @@ -6,7 +6,8 @@ * Public License, v 1. */ -import { +import type { RequestHandlerContext } from 'src/core/server'; +import type { IRouter, RouteConfig, IKibanaResponse, @@ -72,13 +73,12 @@ export interface HttpResourcesServiceToolkit { * }); * @public */ -export type HttpResourcesRequestHandler

= RequestHandler< - P, - Q, - B, - 'get', - KibanaResponseFactory & HttpResourcesServiceToolkit ->; +export type HttpResourcesRequestHandler< + P = unknown, + Q = unknown, + B = unknown, + Context extends RequestHandlerContext = RequestHandlerContext +> = RequestHandler; /** * Allows to configure HTTP response parameters @@ -98,8 +98,8 @@ export interface InternalHttpResourcesSetup { */ export interface HttpResources { /** To register a route handler executing passed function to form response. */ - register: ( + register: ( route: RouteConfig, - handler: HttpResourcesRequestHandler + handler: HttpResourcesRequestHandler ) => void; } diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index ea68c32450647..02b2d0bdf073b 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -11,6 +11,7 @@ import { first, map, publishReplay, tap } from 'rxjs/operators'; import type { PublicMethodsOf } from '@kbn/utility-types'; import { PathConfigType } from '@kbn/utils'; +import type { RequestHandlerContext } from 'src/core/server'; // @ts-expect-error legacy config class import { Config as LegacyConfigClass } from '../../../legacy/server/config'; import { CoreService } from '../../types'; @@ -18,7 +19,14 @@ import { Config } from '../config'; import { CoreContext } from '../core_context'; import { CspConfigType, config as cspConfig } from '../csp'; import { DevConfig, DevConfigType, config as devConfig } from '../dev'; -import { BasePathProxyServer, HttpConfig, HttpConfigType, config as httpConfig } from '../http'; +import { + BasePathProxyServer, + HttpConfig, + HttpConfigType, + config as httpConfig, + IRouter, + RequestHandlerContextProvider, +} from '../http'; import { Logger } from '../logging'; import { LegacyServiceSetupDeps, LegacyServiceStartDeps, LegacyConfig, LegacyVars } from './types'; import { ExternalUrlConfigType, config as externalUrlConfig } from '../external_url'; @@ -225,11 +233,15 @@ export class LegacyService implements CoreService { }, http: { createCookieSessionStorageFactory: setupDeps.core.http.createCookieSessionStorageFactory, - registerRouteHandlerContext: setupDeps.core.http.registerRouteHandlerContext.bind( - null, - this.legacyId - ), - createRouter: () => router, + registerRouteHandlerContext: < + Context extends RequestHandlerContext, + ContextName extends keyof Context + >( + contextName: ContextName, + provider: RequestHandlerContextProvider + ) => setupDeps.core.http.registerRouteHandlerContext(this.legacyId, contextName, provider), + createRouter: () => + router as IRouter, resources: setupDeps.core.httpResources.createRegistrar(router), registerOnPreRouting: setupDeps.core.http.registerOnPreRouting, registerOnPreAuth: setupDeps.core.http.registerOnPreAuth, diff --git a/src/core/server/plugins/plugin_context.ts b/src/core/server/plugins/plugin_context.ts index 1731996b77452..5b0e2ee21a887 100644 --- a/src/core/server/plugins/plugin_context.ts +++ b/src/core/server/plugins/plugin_context.ts @@ -10,6 +10,7 @@ import { map, shareReplay } from 'rxjs/operators'; import { combineLatest } from 'rxjs'; import { PathConfigType, config as pathConfig } from '@kbn/utils'; import { pick, deepFreeze } from '@kbn/std'; +import type { RequestHandlerContext } from 'src/core/server'; import { CoreContext } from '../core_context'; import { PluginWrapper } from './plugin'; import { PluginsServiceSetupDeps, PluginsServiceStartDeps } from './plugins_service'; @@ -24,6 +25,7 @@ import { ElasticsearchConfigType, config as elasticsearchConfig, } from '../elasticsearch/elasticsearch_config'; +import { IRouter, RequestHandlerContextProvider } from '../http'; import { SavedObjectsConfigType, savedObjectsConfig } from '../saved_objects/saved_objects_config'; import { CoreSetup, CoreStart } from '..'; @@ -149,11 +151,15 @@ export function createPluginSetupContext( }, http: { createCookieSessionStorageFactory: deps.http.createCookieSessionStorageFactory, - registerRouteHandlerContext: deps.http.registerRouteHandlerContext.bind( - null, - plugin.opaqueId - ), - createRouter: () => router, + registerRouteHandlerContext: < + Context extends RequestHandlerContext, + ContextName extends keyof Context + >( + contextName: ContextName, + provider: RequestHandlerContextProvider + ) => deps.http.registerRouteHandlerContext(plugin.opaqueId, contextName, provider), + createRouter: () => + router as IRouter, resources: deps.httpResources.createRegistrar(router), registerOnPreRouting: deps.http.registerOnPreRouting, registerOnPreAuth: deps.http.registerOnPreAuth, diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index d0ba6aa1900c7..50d4a5bf502d6 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -132,6 +132,7 @@ import { ReindexParams } from 'elasticsearch'; import { ReindexRethrottleParams } from 'elasticsearch'; import { RenderSearchTemplateParams } from 'elasticsearch'; import { Request } from '@hapi/hapi'; +import { RequestHandlerContext as RequestHandlerContext_2 } from 'src/core/server'; import { ResponseObject } from '@hapi/hapi'; import { ResponseToolkit } from '@hapi/hapi'; import { SchemaTypeError } from '@kbn/config-schema'; @@ -982,7 +983,7 @@ export interface HttpAuth { // @public export interface HttpResources { - register: (route: RouteConfig, handler: HttpResourcesRequestHandler) => void; + register: (route: RouteConfig, handler: HttpResourcesRequestHandler) => void; } // @public @@ -991,7 +992,7 @@ export interface HttpResourcesRenderOptions { } // @public -export type HttpResourcesRequestHandler

= RequestHandler; +export type HttpResourcesRequestHandler

= RequestHandler; // @public export type HttpResourcesResponseOptions = HttpResponseOptions; @@ -1027,7 +1028,7 @@ export interface HttpServiceSetup { auth: HttpAuth; basePath: IBasePath; createCookieSessionStorageFactory: (cookieOptions: SessionStorageCookieOptions) => Promise>; - createRouter: () => IRouter; + createRouter: () => IRouter; csp: ICspConfig; getServerInfo: () => HttpServerInfo; registerAuth: (handler: AuthenticationHandler) => void; @@ -1035,7 +1036,7 @@ export interface HttpServiceSetup { registerOnPreAuth: (handler: OnPreAuthHandler) => void; registerOnPreResponse: (handler: OnPreResponseHandler) => void; registerOnPreRouting: (handler: OnPreRoutingHandler) => void; - registerRouteHandlerContext: (contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; + registerRouteHandlerContext: (contextName: ContextName, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; } // @public (undocumented) @@ -1061,15 +1062,13 @@ export interface IClusterClient { } // @public -export interface IContextContainer> { +export interface IContextContainer { createHandler(pluginOpaqueId: PluginOpaqueId, handler: THandler): (...rest: HandlerParameters) => ShallowPromise>; - registerContext>(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; + registerContext(pluginOpaqueId: PluginOpaqueId, contextName: ContextName, provider: IContextProvider): this; } -// Warning: (ae-forgotten-export) The symbol "PartialExceptFor" needs to be exported by the entry point index.d.ts -// // @public -export type IContextProvider, TContextName extends keyof HandlerContextType> = (context: PartialExceptFor, 'core'>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; +export type IContextProvider = (context: Omit, ...rest: HandlerParameters) => Promise | Context[ContextName]; // @public export interface ICspConfig { @@ -1154,17 +1153,17 @@ export interface IRenderOptions { } // @public -export interface IRouter { - delete: RouteRegistrar<'delete'>; - get: RouteRegistrar<'get'>; +export interface IRouter { + delete: RouteRegistrar<'delete', Context>; + get: RouteRegistrar<'get', Context>; // Warning: (ae-forgotten-export) The symbol "RouterRoute" needs to be exported by the entry point index.d.ts // // @internal getRoutes: () => RouterRoute[]; handleLegacyErrors: RequestHandlerWrapper; - patch: RouteRegistrar<'patch'>; - post: RouteRegistrar<'post'>; - put: RouteRegistrar<'put'>; + patch: RouteRegistrar<'patch', Context>; + post: RouteRegistrar<'post', Context>; + put: RouteRegistrar<'put', Context>; routerPath: string; } @@ -1563,7 +1562,7 @@ export type LegacyElasticsearchClientConfig = Pick = (context: RequestHandlerContext, request: KibanaRequest, response: ResponseFactory) => IKibanaResponse | Promise>; +export type RequestHandler

= (context: Context, request: KibanaRequest, response: ResponseFactory) => IKibanaResponse | Promise>; // @public export interface RequestHandlerContext { @@ -1930,13 +1929,13 @@ export interface RequestHandlerContext { } // @public -export type RequestHandlerContextContainer = IContextContainer>; +export type RequestHandlerContextContainer = IContextContainer; // @public -export type RequestHandlerContextProvider = IContextProvider, TContextName>; +export type RequestHandlerContextProvider = IContextProvider; // @public -export type RequestHandlerWrapper = (handler: RequestHandler) => RequestHandler; +export type RequestHandlerWrapper = (handler: RequestHandler) => RequestHandler; // @public export interface ResolveCapabilitiesOptions { @@ -1989,7 +1988,7 @@ export type RouteContentType = 'application/json' | 'application/*+json' | 'appl export type RouteMethod = SafeRouteMethod | DestructiveRouteMethod; // @public -export type RouteRegistrar = (route: RouteConfig, handler: RequestHandler) => void; +export type RouteRegistrar = (route: RouteConfig, handler: RequestHandler) => void; // @public export class RouteValidationError extends SchemaTypeError { diff --git a/src/core/server/server.ts b/src/core/server/server.ts index a58aae7e0ff26..60f3f90428d40 100644 --- a/src/core/server/server.ts +++ b/src/core/server/server.ts @@ -294,7 +294,7 @@ export class Server { coreSetup.http.registerRouteHandlerContext( coreId, 'core', - async (context, req, res): Promise => { + (context, req, res): RequestHandlerContext['core'] => { return new CoreRouteHandlerContext(this.coreStart!, req); } ); diff --git a/src/core/utils/context.test.ts b/src/core/utils/context.test.ts deleted file mode 100644 index 42cb8d635ae02..0000000000000 --- a/src/core/utils/context.test.ts +++ /dev/null @@ -1,268 +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 - * and the Server Side Public License, v 1; you may not use this file except in - * compliance with, at your election, the Elastic License or the Server Side - * Public License, v 1. - */ - -import { ContextContainer } from './context'; -import { PluginOpaqueId } from '../server'; - -const pluginA = Symbol('pluginA'); -const pluginB = Symbol('pluginB'); -const pluginC = Symbol('pluginC'); -const pluginD = Symbol('pluginD'); -const plugins: ReadonlyMap = new Map([ - [pluginA, []], - [pluginB, [pluginA]], - [pluginC, [pluginA, pluginB]], - [pluginD, []], -]); - -interface MyContext { - core1: string; - core2: number; - ctxFromA: string; - ctxFromB: number; - ctxFromC: boolean; - ctxFromD: object; -} - -const coreId = Symbol(); - -describe('ContextContainer', () => { - it('does not allow the same context to be registered twice', () => { - const contextContainer = new ContextContainer<(context: MyContext) => string>(plugins, coreId); - contextContainer.registerContext(coreId, 'ctxFromA', () => 'aString'); - - expect(() => - contextContainer.registerContext(coreId, 'ctxFromA', () => 'aString') - ).toThrowErrorMatchingInlineSnapshot( - `"Context provider for ctxFromA has already been registered."` - ); - }); - - describe('registerContext', () => { - it('throws error if called with an unknown symbol', async () => { - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - await expect(() => - contextContainer.registerContext(Symbol('unknown'), 'ctxFromA', jest.fn()) - ).toThrowErrorMatchingInlineSnapshot( - `"Cannot register context for unknown plugin: Symbol(unknown)"` - ); - }); - }); - - describe('context building', () => { - it('resolves dependencies', async () => { - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - expect.assertions(8); - contextContainer.registerContext(coreId, 'core1', (context) => { - expect(context).toEqual({}); - return 'core'; - }); - - contextContainer.registerContext(pluginA, 'ctxFromA', (context) => { - expect(context).toEqual({ core1: 'core' }); - return 'aString'; - }); - contextContainer.registerContext(pluginB, 'ctxFromB', (context) => { - expect(context).toEqual({ core1: 'core', ctxFromA: 'aString' }); - return 299; - }); - contextContainer.registerContext(pluginC, 'ctxFromC', (context) => { - expect(context).toEqual({ core1: 'core', ctxFromA: 'aString', ctxFromB: 299 }); - return false; - }); - contextContainer.registerContext(pluginD, 'ctxFromD', (context) => { - expect(context).toEqual({ core1: 'core' }); - return {}; - }); - - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(pluginC, rawHandler1); - - const rawHandler2 = jest.fn(() => 'handler2'); - const handler2 = contextContainer.createHandler(pluginD, rawHandler2); - - await handler1(); - await handler2(); - - // Should have context from pluginC, its deps, and core - expect(rawHandler1).toHaveBeenCalledWith({ - core1: 'core', - ctxFromA: 'aString', - ctxFromB: 299, - ctxFromC: false, - }); - - // Should have context from pluginD, and core - expect(rawHandler2).toHaveBeenCalledWith({ - core1: 'core', - ctxFromD: {}, - }); - }); - - it('exposes all core context to all providers regardless of registration order', async () => { - expect.assertions(4); - - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - contextContainer - .registerContext(pluginA, 'ctxFromA', (context) => { - expect(context).toEqual({ core1: 'core', core2: 101 }); - return `aString ${context.core1} ${context.core2}`; - }) - .registerContext(coreId, 'core1', () => 'core') - .registerContext(coreId, 'core2', () => 101) - .registerContext(pluginB, 'ctxFromB', (context) => { - expect(context).toEqual({ core1: 'core', core2: 101, ctxFromA: 'aString core 101' }); - return 277; - }); - - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(pluginB, rawHandler1); - - expect(await handler1()).toEqual('handler1'); - - expect(rawHandler1).toHaveBeenCalledWith({ - core1: 'core', - core2: 101, - ctxFromA: 'aString core 101', - ctxFromB: 277, - }); - }); - - it('exposes all core context to core providers', async () => { - expect.assertions(4); - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - - contextContainer - .registerContext(coreId, 'core1', (context) => { - expect(context).toEqual({}); - return 'core'; - }) - .registerContext(coreId, 'core2', (context) => { - expect(context).toEqual({ core1: 'core' }); - return 101; - }); - - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(pluginA, rawHandler1); - - expect(await handler1()).toEqual('handler1'); - - // If no context is registered for pluginA, only core contexts should be exposed - expect(rawHandler1).toHaveBeenCalledWith({ - core1: 'core', - core2: 101, - }); - }); - - it('does not expose plugin contexts to core handler', async () => { - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - - contextContainer - .registerContext(coreId, 'core1', (context) => 'core') - .registerContext(pluginA, 'ctxFromA', (context) => 'aString'); - - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(coreId, rawHandler1); - - expect(await handler1()).toEqual('handler1'); - // pluginA context should not be present in a core handler - expect(rawHandler1).toHaveBeenCalledWith({ - core1: 'core', - }); - }); - - it('passes additional arguments to providers', async () => { - expect.assertions(6); - const contextContainer = new ContextContainer< - (context: MyContext, arg1: string, arg2: number) => string - >(plugins, coreId); - - contextContainer.registerContext(coreId, 'core1', (context, str, num) => { - expect(str).toEqual('passed string'); - expect(num).toEqual(77); - return `core ${str}`; - }); - - contextContainer.registerContext(pluginD, 'ctxFromD', (context, str, num) => { - expect(str).toEqual('passed string'); - expect(num).toEqual(77); - return { - num: 77, - }; - }); - - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(pluginD, rawHandler1); - - expect(await handler1('passed string', 77)).toEqual('handler1'); - - expect(rawHandler1).toHaveBeenCalledWith( - { - core1: 'core passed string', - ctxFromD: { - num: 77, - }, - }, - 'passed string', - 77 - ); - }); - }); - - describe('createHandler', () => { - it('throws error if called with an unknown symbol', async () => { - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - await expect(() => - contextContainer.createHandler(Symbol('unknown'), jest.fn()) - ).toThrowErrorMatchingInlineSnapshot( - `"Cannot create handler for unknown plugin: Symbol(unknown)"` - ); - }); - - it('returns value from original handler', async () => { - const contextContainer = new ContextContainer<(context: MyContext) => string>( - plugins, - coreId - ); - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(pluginA, rawHandler1); - - expect(await handler1()).toEqual('handler1'); - }); - - it('passes additional arguments to handlers', async () => { - const contextContainer = new ContextContainer< - (context: MyContext, arg1: string, arg2: number) => string - >(plugins, coreId); - - const rawHandler1 = jest.fn(() => 'handler1'); - const handler1 = contextContainer.createHandler(pluginA, rawHandler1); - - await handler1('passed string', 77); - expect(rawHandler1).toHaveBeenCalledWith({}, 'passed string', 77); - }); - }); -}); diff --git a/src/core/utils/index.ts b/src/core/utils/index.ts index 0a480606b9990..d365b15866c3f 100644 --- a/src/core/utils/index.ts +++ b/src/core/utils/index.ts @@ -6,12 +6,4 @@ * Public License, v 1. */ -export { - ContextContainer, - HandlerContextType, - HandlerFunction, - HandlerParameters, - IContextContainer, - IContextProvider, -} from './context'; export { DEFAULT_APP_CATEGORIES } from './default_app_categories'; diff --git a/src/plugins/bfetch/server/plugin.ts b/src/plugins/bfetch/server/plugin.ts index 2613104312ba5..55eadf5212f3a 100644 --- a/src/plugins/bfetch/server/plugin.ts +++ b/src/plugins/bfetch/server/plugin.ts @@ -6,7 +6,7 @@ * Public License, v 1. */ -import { +import type { CoreStart, PluginInitializerContext, CoreSetup, @@ -15,6 +15,7 @@ import { KibanaRequest, RouteMethod, RequestHandler, + RequestHandlerContext, } from 'src/core/server'; import { schema } from '@kbn/config-schema'; import { Subject } from 'rxjs'; @@ -77,9 +78,16 @@ export interface BfetchServerSetup { * * @param streamHandler */ - createStreamingRequestHandler: ( + createStreamingRequestHandler: < + Response, + P, + Q, + B, + Context extends RequestHandlerContext = RequestHandlerContext, + Method extends RouteMethod = any + >( streamHandler: StreamingRequestHandler - ) => RequestHandler; + ) => RequestHandler; } // eslint-disable-next-line diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 34b4dc9116302..048d60dbc25c6 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -2369,7 +2369,7 @@ export class SearchSource { removeField(field: K): this; serialize(): { searchSourceJSON: string; - references: import("src/core/server").SavedObjectReference[]; + references: import("../../../../../core/types").SavedObjectReference[]; }; setField(field: K, value: SearchSourceFields[K]): this; setFields(newFields: SearchSourceFields): this; diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 72eb0015215d1..27af11674d061 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -235,6 +235,8 @@ export { SearchUsage, SessionService, ISessionService, + DataApiRequestHandlerContext, + DataRequestHandlerContext, } from './search'; // Search namespace diff --git a/src/plugins/data/server/index_patterns/routes/util/handle_errors.ts b/src/plugins/data/server/index_patterns/routes/util/handle_errors.ts index bede9165de08c..9b4268cfd53c9 100644 --- a/src/plugins/data/server/index_patterns/routes/util/handle_errors.ts +++ b/src/plugins/data/server/index_patterns/routes/util/handle_errors.ts @@ -6,7 +6,7 @@ * Public License, v 1. */ -import { RequestHandler, RouteMethod } from 'src/core/server'; +import type { RequestHandler, RouteMethod, RequestHandlerContext } from 'src/core/server'; import { ErrorIndexPatternNotFound } from '../../error'; interface ErrorResponseBody { @@ -29,9 +29,15 @@ interface ErrorWithData { * } * ``` */ -export const handleErrors = ( - handler: RequestHandler -): RequestHandler => async (context, request, response) => { +export const handleErrors = < + P, + Q, + B, + Context extends RequestHandlerContext, + Method extends RouteMethod +>( + handler: RequestHandler +): RequestHandler => async (context, request, response) => { try { return await handler(context, request, response); } catch (error) { diff --git a/src/plugins/data/server/search/routes/msearch.ts b/src/plugins/data/server/search/routes/msearch.ts index 5b62d6732430f..70bb56afa4403 100644 --- a/src/plugins/data/server/search/routes/msearch.ts +++ b/src/plugins/data/server/search/routes/msearch.ts @@ -8,12 +8,11 @@ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; import { SearchRouteDependencies } from '../search_service'; import { getCallMsearch } from './call_msearch'; import { reportServerError } from '../../../../kibana_utils/server'; - +import type { DataPluginRouter } from '../types'; /** * The msearch route takes in an array of searches, each consisting of header * and body json, and reformts them into a single request for the _msearch API. @@ -27,7 +26,10 @@ import { reportServerError } from '../../../../kibana_utils/server'; * * @deprecated */ -export function registerMsearchRoute(router: IRouter, deps: SearchRouteDependencies): void { +export function registerMsearchRoute( + router: DataPluginRouter, + deps: SearchRouteDependencies +): void { router.post( { path: '/internal/_msearch', diff --git a/src/plugins/data/server/search/routes/search.ts b/src/plugins/data/server/search/routes/search.ts index 5969dd1324376..6d2da4c1e63dd 100644 --- a/src/plugins/data/server/search/routes/search.ts +++ b/src/plugins/data/server/search/routes/search.ts @@ -8,12 +8,12 @@ import { first } from 'rxjs/operators'; import { schema } from '@kbn/config-schema'; -import type { IRouter } from 'src/core/server'; import { getRequestAbortedSignal } from '../../lib'; import { shimHitsTotal } from './shim_hits_total'; import { reportServerError } from '../../../../kibana_utils/server'; +import type { DataPluginRouter } from '../types'; -export function registerSearchRoute(router: IRouter): void { +export function registerSearchRoute(router: DataPluginRouter): void { router.post( { path: '/internal/search/{strategy}/{id?}', diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index 762b1bffc7c11..f1a6fc09ee21f 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -21,12 +21,13 @@ import { import { catchError, first, map } from 'rxjs/operators'; import { BfetchServerSetup } from 'src/plugins/bfetch/server'; import { ExpressionsServerSetup } from 'src/plugins/expressions/server'; -import { +import type { ISearchSetup, ISearchStart, ISearchStrategy, SearchEnhancements, SearchStrategyDependencies, + DataRequestHandlerContext, } from './types'; import { AggsService } from './aggs'; @@ -64,12 +65,6 @@ import { ConfigSchema } from '../../config'; import { SessionService, IScopedSessionService, ISessionService } from './session'; import { KbnServerError } from '../../../kibana_utils/server'; -declare module 'src/core/server' { - interface RequestHandlerContext { - search?: ISearchClient & { session: IScopedSessionService }; - } -} - type StrategyMap = Record>; /** @internal */ @@ -112,7 +107,7 @@ export class SearchService implements Plugin { ): ISearchSetup { const usage = usageCollection ? usageProvider(core) : undefined; - const router = core.http.createRouter(); + const router = core.http.createRouter(); const routeDependencies = { getStartServices: core.getStartServices, globalConfig$: this.initializerContext.config.legacy.globalConfig$, @@ -124,11 +119,14 @@ export class SearchService implements Plugin { this.coreStart = coreStart; }); - core.http.registerRouteHandlerContext('search', async (context, request) => { - const search = this.asScopedProvider(this.coreStart!)(request); - const session = this.sessionService.asScopedProvider(this.coreStart!)(request); - return { ...search, session }; - }); + core.http.registerRouteHandlerContext( + 'search', + async (context, request) => { + const search = this.asScopedProvider(this.coreStart!)(request); + const session = this.sessionService.asScopedProvider(this.coreStart!)(request); + return { ...search, session }; + } + ); this.registerSearchStrategy( ES_SEARCH_STRATEGY, diff --git a/src/plugins/data/server/search/types.ts b/src/plugins/data/server/search/types.ts index d292282f8a435..7e7d22fdb2be1 100644 --- a/src/plugins/data/server/search/types.ts +++ b/src/plugins/data/server/search/types.ts @@ -7,11 +7,13 @@ */ import { Observable } from 'rxjs'; -import { +import type { + IRouter, IScopedClusterClient, IUiSettingsClient, SavedObjectsClientContract, KibanaRequest, + RequestHandlerContext, } from 'src/core/server'; import { ISearchOptions, @@ -23,7 +25,7 @@ import { import { AggsSetup, AggsStart } from './aggs'; import { SearchUsage } from './collectors'; import { IEsSearchRequest, IEsSearchResponse } from './es_search'; -import { ISessionService } from './session'; +import { ISessionService, IScopedSessionService } from './session'; export interface SearchEnhancements { defaultStrategy: string; @@ -101,3 +103,16 @@ export interface ISearchStart< asScoped: (request: KibanaRequest) => Promise; }; } + +export interface DataApiRequestHandlerContext extends ISearchClient { + session: IScopedSessionService; +} + +/** + * @internal + */ +export interface DataRequestHandlerContext extends RequestHandlerContext { + search: DataApiRequestHandlerContext; +} + +export type DataPluginRouter = IRouter; diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 84a82511d5a5e..ef8015ecaca26 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -53,6 +53,7 @@ import { PluginInitializerContext as PluginInitializerContext_2 } from 'src/core import { PublicMethodsOf } from '@kbn/utility-types'; import { RecursiveReadonly } from '@kbn/utility-types'; import { RequestAdapter } from 'src/plugins/inspector/common'; +import { RequestHandlerContext } from 'src/core/server'; import { RequestStatistics } from 'src/plugins/inspector/common'; import { SavedObject } from 'src/core/server'; import { SavedObjectsClientContract } from 'src/core/server'; @@ -304,6 +305,23 @@ export const castEsToKbnFieldTypeName: (esType: ES_FIELD_TYPES | string) => KBN_ // @public (undocumented) export const config: PluginConfigDescriptor; +// Warning: (ae-forgotten-export) The symbol "ISearchClient" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "DataApiRequestHandlerContext" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface DataApiRequestHandlerContext extends ISearchClient { + // Warning: (ae-forgotten-export) The symbol "IScopedSessionService" needs to be exported by the entry point index.d.ts + // + // (undocumented) + session: IScopedSessionService; +} + +// @internal (undocumented) +export interface DataRequestHandlerContext extends RequestHandlerContext { + // (undocumented) + search: DataApiRequestHandlerContext; +} + // @public (undocumented) export enum ES_FIELD_TYPES { // (undocumented) @@ -923,8 +941,6 @@ export interface ISearchStart ISearchClient; getSearchStrategy: (name?: string) => ISearchStrategy; @@ -950,8 +966,6 @@ export interface ISearchStrategy (request: KibanaRequest) => IScopedSessionService; } @@ -1115,10 +1129,10 @@ export class Plugin implements Plugin_2 Promise; + fieldFormatServiceFactory: (uiSettings: import("../../../core/server").IUiSettingsClient) => Promise; }; indexPatterns: { - indexPatternsServiceFactory: (savedObjectsClient: Pick, elasticsearchClient: import("src/core/server").ElasticsearchClient) => Promise; + indexPatternsServiceFactory: (savedObjectsClient: Pick, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise; }; search: ISearchStart>; }; @@ -1405,23 +1419,23 @@ export function usageProvider(core: CoreSetup_2): SearchUsage; // src/plugins/data/server/index.ts:100:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:126:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:126:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:241:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:241:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:241:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:241:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:243:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:244:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:253:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:254:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:255:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:259:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:260:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:264:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:267:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:268:1 - (ae-forgotten-export) The symbol "calcAutoIntervalLessThan" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:243:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:243:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:243:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:243:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:245:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:246:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:255:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:256:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:257:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:261:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:262:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:266:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:269:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:270:1 - (ae-forgotten-export) The symbol "calcAutoIntervalLessThan" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index_patterns/index_patterns_service.ts:59:14 - (ae-forgotten-export) The symbol "IndexPatternsService" needs to be exported by the entry point index.d.ts // src/plugins/data/server/plugin.ts:79:74 - (ae-forgotten-export) The symbol "DataEnhancements" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/search/types.ts:101:5 - (ae-forgotten-export) The symbol "ISearchStartSearchSource" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/search/types.ts:103:5 - (ae-forgotten-export) The symbol "ISearchStartSearchSource" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) diff --git a/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.test.ts b/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.test.ts index 457052decd65b..ff73261d173d7 100644 --- a/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.test.ts +++ b/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.test.ts @@ -36,7 +36,7 @@ describe('sendTelemetryOptInStatus', () => { expect(fetch).toBeCalledTimes(1); expect(fetch).toBeCalledWith(mockConfig.optInStatusUrl, { method: 'post', - body: mockOptInStatus, + body: '["mock_opt_in_hashed_value"]', headers: { 'X-Elastic-Stack-Version': mockConfig.currentKibanaVersion }, }); }); diff --git a/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts b/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts index 33648769f170a..1d23a49fc33ed 100644 --- a/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts +++ b/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts @@ -6,7 +6,6 @@ * Public License, v 1. */ -// @ts-ignore import fetch from 'node-fetch'; import { IRouter } from 'kibana/server'; @@ -35,7 +34,7 @@ export async function sendTelemetryOptInStatus( await fetch(optInStatusUrl, { method: 'post', - body: optInStatus, + body: JSON.stringify(optInStatus), headers: { 'X-Elastic-Stack-Version': currentKibanaVersion }, }); } diff --git a/src/plugins/vis_type_timelion/server/plugin.ts b/src/plugins/vis_type_timelion/server/plugin.ts index b41eecfc0c63a..f999c1dfc773a 100644 --- a/src/plugins/vis_type_timelion/server/plugin.ts +++ b/src/plugins/vis_type_timelion/server/plugin.ts @@ -11,8 +11,12 @@ import { first } from 'rxjs/operators'; import { TypeOf, schema } from '@kbn/config-schema'; import { RecursiveReadonly } from '@kbn/utility-types'; import { deepFreeze } from '@kbn/std'; +import type { RequestHandlerContext } from 'src/core/server'; -import { PluginStart } from '../../../../src/plugins/data/server'; +import type { + PluginStart, + DataApiRequestHandlerContext, +} from '../../../../src/plugins/data/server'; import { CoreSetup, PluginInitializerContext } from '../../../../src/core/server'; import { configSchema } from '../config'; import loadFunctions from './lib/load_functions'; @@ -67,7 +71,9 @@ export class Plugin { const logger = this.initializerContext.logger.get('timelion'); - const router = core.http.createRouter(); + const router = core.http.createRouter< + RequestHandlerContext & { search: DataApiRequestHandlerContext } + >(); const deps = { configManager, @@ -79,7 +85,7 @@ export class Plugin { functionsRoute(router, deps); runRoute(router, deps); - validateEsRoute(router, core); + validateEsRoute(router); core.uiSettings.register({ 'timelion:es.timefield': { diff --git a/src/plugins/vis_type_timelion/server/routes/validate_es.ts b/src/plugins/vis_type_timelion/server/routes/validate_es.ts index 242029a492e92..1637fcc464f46 100644 --- a/src/plugins/vis_type_timelion/server/routes/validate_es.ts +++ b/src/plugins/vis_type_timelion/server/routes/validate_es.ts @@ -7,9 +7,12 @@ */ import _ from 'lodash'; -import { IRouter, CoreSetup } from 'kibana/server'; +import { IRouter, RequestHandlerContext } from 'kibana/server'; +import type { DataApiRequestHandlerContext } from '../../../data/server'; -export function validateEsRoute(router: IRouter, core: CoreSetup) { +export function validateEsRoute( + router: IRouter +) { router.get( { path: '/api/timelion/validate/es', diff --git a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts index 8bcafa685a275..dc075930cf256 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts @@ -8,14 +8,15 @@ import { uniqBy } from 'lodash'; import { first, map } from 'rxjs/operators'; -import { KibanaRequest, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest } from 'kibana/server'; import { Framework } from '../plugin'; import { IndexPatternsFetcher } from '../../../data/server'; import { ReqFacade } from './search_strategies/strategies/abstract_search_strategy'; +import { VisTypeTimeseriesRequestHandlerContext } from '../types'; export async function getFields( - requestContext: RequestHandlerContext, + requestContext: VisTypeTimeseriesRequestHandlerContext, request: KibanaRequest, framework: Framework, indexPatternString: string diff --git a/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts b/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts index 81881d5bda4ef..3b1e9d373f136 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts @@ -6,7 +6,7 @@ * Public License, v 1. */ -import { FakeRequest, RequestHandlerContext } from 'kibana/server'; +import { FakeRequest } from 'kibana/server'; import _ from 'lodash'; import { first, map } from 'rxjs/operators'; @@ -15,6 +15,7 @@ import { getPanelData } from './vis_data/get_panel_data'; import { Framework } from '../plugin'; import { ReqFacade } from './search_strategies/strategies/abstract_search_strategy'; import { TimeseriesVisData } from '../../common/types'; +import type { VisTypeTimeseriesRequestHandlerContext } from '../types'; export interface GetVisDataOptions { timerange: { @@ -30,13 +31,13 @@ export interface GetVisDataOptions { } export type GetVisData = ( - requestContext: RequestHandlerContext, + requestContext: VisTypeTimeseriesRequestHandlerContext, options: GetVisDataOptions, framework: Framework ) => Promise; export function getVisData( - requestContext: RequestHandlerContext, + requestContext: VisTypeTimeseriesRequestHandlerContext, request: FakeRequest & { body: GetVisDataOptions }, framework: Framework ): Promise { diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts index 871baf959645d..966daca87a208 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts @@ -6,12 +6,7 @@ * Public License, v 1. */ -import type { - RequestHandlerContext, - FakeRequest, - IUiSettingsClient, - SavedObjectsClientContract, -} from 'kibana/server'; +import type { FakeRequest, IUiSettingsClient, SavedObjectsClientContract } from 'kibana/server'; import type { Framework } from '../../../plugin'; import type { IndexPatternsFetcher, IFieldType } from '../../../../../data/server'; @@ -19,6 +14,7 @@ import type { VisPayload } from '../../../../common/types'; import type { IndexPatternsService } from '../../../../../data/common'; import { indexPatterns } from '../../../../../data/server'; import { SanitizedFieldType } from '../../../../common/types'; +import type { VisTypeTimeseriesRequestHandlerContext } from '../../../types'; /** * ReqFacade is a regular KibanaRequest object extended with additional service @@ -27,7 +23,7 @@ import { SanitizedFieldType } from '../../../../common/types'; * This will be replaced by standard KibanaRequest and RequestContext objects in a later version. */ export interface ReqFacade extends FakeRequest { - requestContext: RequestHandlerContext; + requestContext: VisTypeTimeseriesRequestHandlerContext; framework: Framework; payload: T; pre: { @@ -58,8 +54,8 @@ export abstract class AbstractSearchStrategy { bodies.forEach((body) => { requests.push( - req.requestContext - .search!.search( + req.requestContext.search + .search( { indexType, params: { diff --git a/src/plugins/vis_type_timeseries/server/plugin.ts b/src/plugins/vis_type_timeseries/server/plugin.ts index bd483e3f0f72e..adcd7e8bbf0d5 100644 --- a/src/plugins/vis_type_timeseries/server/plugin.ts +++ b/src/plugins/vis_type_timeseries/server/plugin.ts @@ -11,9 +11,7 @@ import { CoreSetup, CoreStart, Plugin, - RequestHandlerContext, Logger, - IRouter, FakeRequest, } from 'src/core/server'; import { Observable } from 'rxjs'; @@ -27,6 +25,7 @@ import { visDataRoutes } from './routes/vis'; import { fieldsRoutes } from './routes/fields'; import { SearchStrategyRegistry } from './lib/search_strategies'; import { uiSettings } from './ui_settings'; +import type { VisTypeTimeseriesRequestHandlerContext, VisTypeTimeseriesRouter } from './types'; export interface LegacySetup { server: Server; @@ -42,7 +41,7 @@ interface VisTypeTimeseriesPluginStartDependencies { export interface VisTypeTimeseriesSetup { getVisData: ( - requestContext: RequestHandlerContext, + requestContext: VisTypeTimeseriesRequestHandlerContext, fakeRequest: FakeRequest, options: GetVisDataOptions ) => ReturnType; @@ -55,7 +54,7 @@ export interface Framework { config$: Observable; globalConfig$: PluginInitializerContext['config']['legacy']['globalConfig$']; logger: Logger; - router: IRouter; + router: VisTypeTimeseriesRouter; searchStrategyRegistry: SearchStrategyRegistry; } @@ -73,7 +72,7 @@ export class VisTypeTimeseriesPlugin implements Plugin { const config$ = this.initializerContext.config.create(); // Global config contains things like the ES shard timeout const globalConfig$ = this.initializerContext.config.legacy.globalConfig$; - const router = core.http.createRouter(); + const router = core.http.createRouter(); const searchStrategyRegistry = new SearchStrategyRegistry(); @@ -92,7 +91,7 @@ export class VisTypeTimeseriesPlugin implements Plugin { return { getVisData: async ( - requestContext: RequestHandlerContext, + requestContext: VisTypeTimeseriesRequestHandlerContext, fakeRequest: FakeRequest, options: GetVisDataOptions ) => { diff --git a/src/plugins/vis_type_timeseries/server/routes/vis.ts b/src/plugins/vis_type_timeseries/server/routes/vis.ts index fd9dfc18eadff..d1fcaa97b3053 100644 --- a/src/plugins/vis_type_timeseries/server/routes/vis.ts +++ b/src/plugins/vis_type_timeseries/server/routes/vis.ts @@ -6,17 +6,18 @@ * Public License, v 1. */ -import { IRouter, KibanaRequest } from 'kibana/server'; +import { KibanaRequest } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { ensureNoUnsafeProperties } from '@kbn/std'; import { getVisData, GetVisDataOptions } from '../lib/get_vis_data'; import { visPayloadSchema } from '../../common/vis_schema'; import { ROUTES } from '../../common/constants'; import { Framework } from '../plugin'; +import type { VisTypeTimeseriesRouter } from '../types'; const escapeHatch = schema.object({}, { unknowns: 'allow' }); -export const visDataRoutes = (router: IRouter, framework: Framework) => { +export const visDataRoutes = (router: VisTypeTimeseriesRouter, framework: Framework) => { router.post( { path: ROUTES.VIS_DATA, diff --git a/src/plugins/vis_type_timeseries/server/types.ts b/src/plugins/vis_type_timeseries/server/types.ts new file mode 100644 index 0000000000000..29cd33031c883 --- /dev/null +++ b/src/plugins/vis_type_timeseries/server/types.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * and the Server Side Public License, v 1; you may not use this file except in + * compliance with, at your election, the Elastic License or the Server Side + * Public License, v 1. + */ + +import type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { DataApiRequestHandlerContext } from '../../data/server'; + +export interface VisTypeTimeseriesRequestHandlerContext extends RequestHandlerContext { + search: DataApiRequestHandlerContext; +} + +export type VisTypeTimeseriesRouter = IRouter; diff --git a/test/plugin_functional/plugins/core_plugin_a/server/index.ts b/test/plugin_functional/plugins/core_plugin_a/server/index.ts index 2134b88eae84a..f98b5772c7e5f 100644 --- a/test/plugin_functional/plugins/core_plugin_a/server/index.ts +++ b/test/plugin_functional/plugins/core_plugin_a/server/index.ts @@ -7,6 +7,6 @@ */ import { CorePluginAPlugin } from './plugin'; -export { PluginARequestContext } from './plugin'; +export { PluginAApiRequestContext } from './plugin'; export const plugin = () => new CorePluginAPlugin(); diff --git a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts index b49336f2d3e1f..367168afdc1de 100644 --- a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts +++ b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts @@ -6,26 +6,27 @@ * Public License, v 1. */ -import { Plugin, CoreSetup } from 'kibana/server'; +import type { Plugin, CoreSetup, RequestHandlerContext } from 'kibana/server'; -export interface PluginARequestContext { +export interface PluginAApiRequestContext { ping: () => Promise; } -declare module 'kibana/server' { - interface RequestHandlerContext { - pluginA?: PluginARequestContext; - } +interface PluginARequstHandlerContext extends RequestHandlerContext { + pluginA: PluginAApiRequestContext; } export class CorePluginAPlugin implements Plugin { public setup(core: CoreSetup, deps: {}) { - core.http.registerRouteHandlerContext('pluginA', (context) => { - return { - ping: () => - context.core.elasticsearch.legacy.client.callAsInternalUser('ping') as Promise, - }; - }); + core.http.registerRouteHandlerContext( + 'pluginA', + (context) => { + return { + ping: () => + context.core.elasticsearch.legacy.client.callAsInternalUser('ping') as Promise, + }; + } + ); } public start() {} diff --git a/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts index 528f996915885..fba19a46fc7e9 100644 --- a/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts +++ b/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts @@ -6,19 +6,17 @@ * Public License, v 1. */ -import { Plugin, CoreSetup } from 'kibana/server'; +import { Plugin, CoreSetup, RequestHandlerContext } from 'kibana/server'; import { schema } from '@kbn/config-schema'; -import { PluginARequestContext } from '../../core_plugin_a/server'; +import { PluginAApiRequestContext } from '../../core_plugin_a/server'; -declare module 'kibana/server' { - interface RequestHandlerContext { - pluginA?: PluginARequestContext; - } +interface PluginBContext extends RequestHandlerContext { + pluginA: PluginAApiRequestContext; } export class CorePluginBPlugin implements Plugin { public setup(core: CoreSetup, deps: {}) { - const router = core.http.createRouter(); + const router = core.http.createRouter(); router.get({ path: '/core_plugin_b', validate: false }, async (context, req, res) => { if (!context.pluginA) return res.internalError({ body: 'pluginA is disabled' }); const response = await context.pluginA.ping(); diff --git a/test/plugin_functional/plugins/core_plugin_route_timeouts/server/index.ts b/test/plugin_functional/plugins/core_plugin_route_timeouts/server/index.ts index 6569d89f9d0b6..5b58c308d5097 100644 --- a/test/plugin_functional/plugins/core_plugin_route_timeouts/server/index.ts +++ b/test/plugin_functional/plugins/core_plugin_route_timeouts/server/index.ts @@ -7,6 +7,5 @@ */ import { CorePluginRouteTimeoutsPlugin } from './plugin'; -export { PluginARequestContext } from './plugin'; export const plugin = () => new CorePluginRouteTimeoutsPlugin(); diff --git a/test/plugin_functional/plugins/core_plugin_route_timeouts/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_route_timeouts/server/plugin.ts index e9e97288a1156..a6d964fdeb7d4 100644 --- a/test/plugin_functional/plugins/core_plugin_route_timeouts/server/plugin.ts +++ b/test/plugin_functional/plugins/core_plugin_route_timeouts/server/plugin.ts @@ -9,16 +9,6 @@ import { Plugin, CoreSetup } from 'kibana/server'; import { schema } from '@kbn/config-schema'; -export interface PluginARequestContext { - ping: () => Promise; -} - -declare module 'kibana/server' { - interface RequestHandlerContext { - pluginA?: PluginARequestContext; - } -} - export class CorePluginRouteTimeoutsPlugin implements Plugin { public setup(core: CoreSetup, deps: {}) { const { http } = core; diff --git a/x-pack/plugins/actions/server/index.ts b/x-pack/plugins/actions/server/index.ts index c43cc20bd4773..6c4857bff4e81 100644 --- a/x-pack/plugins/actions/server/index.ts +++ b/x-pack/plugins/actions/server/index.ts @@ -14,12 +14,13 @@ import { ActionsConfigType } from './types'; export type ActionsClient = PublicMethodsOf; export type ActionsAuthorization = PublicMethodsOf; -export { +export type { ActionsPlugin, ActionResult, ActionTypeExecutorOptions, ActionType, PreConfiguredAction, + ActionsApiRequestHandlerContext, } from './types'; export type { @@ -45,7 +46,7 @@ export type { TeamsActionParams, } from './builtin_action_types'; -export { PluginSetupContract, PluginStartContract } from './plugin'; +export type { PluginSetupContract, PluginStartContract } from './plugin'; export { asSavedObjectExecutionSource, asHttpRequestExecutionSource } from './lib'; diff --git a/x-pack/plugins/actions/server/plugin.test.ts b/x-pack/plugins/actions/server/plugin.test.ts index ff43b05b6d895..d1e40563c0172 100644 --- a/x-pack/plugins/actions/server/plugin.test.ts +++ b/x-pack/plugins/actions/server/plugin.test.ts @@ -12,7 +12,7 @@ import { featuresPluginMock } from '../../features/server/mocks'; import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks'; import { taskManagerMock } from '../../task_manager/server/mocks'; import { eventLogMock } from '../../event_log/server/mocks'; -import { ActionType } from './types'; +import { ActionType, ActionsApiRequestHandlerContext } from './types'; import { ActionsConfig } from './config'; import { ActionsPlugin, @@ -73,7 +73,10 @@ describe('Actions Plugin', () => { }); expect(coreSetup.http.registerRouteHandlerContext).toHaveBeenCalledTimes(1); - const handler = coreSetup.http.registerRouteHandlerContext.mock.calls[0]; + const handler = coreSetup.http.registerRouteHandlerContext.mock.calls[0] as [ + string, + Function + ]; expect(handler[0]).toEqual('actions'); const actionsContextHandler = ((await handler[1]( @@ -91,7 +94,7 @@ describe('Actions Plugin', () => { } as unknown) as RequestHandlerContext, httpServerMock.createKibanaRequest(), httpServerMock.createResponseFactory() - )) as unknown) as RequestHandlerContext['actions']; + )) as unknown) as ActionsApiRequestHandlerContext; actionsContextHandler!.getActionsClient(); }); @@ -101,7 +104,10 @@ describe('Actions Plugin', () => { await plugin.setup(coreSetup as any, pluginsSetup); expect(coreSetup.http.registerRouteHandlerContext).toHaveBeenCalledTimes(1); - const handler = coreSetup.http.registerRouteHandlerContext.mock.calls[0]; + const handler = coreSetup.http.registerRouteHandlerContext.mock.calls[0] as [ + string, + Function + ]; expect(handler[0]).toEqual('actions'); const actionsContextHandler = ((await handler[1]( @@ -114,7 +120,7 @@ describe('Actions Plugin', () => { } as unknown) as RequestHandlerContext, httpServerMock.createKibanaRequest(), httpServerMock.createResponseFactory() - )) as unknown) as RequestHandlerContext['actions']; + )) as unknown) as ActionsApiRequestHandlerContext; expect(() => actionsContextHandler!.getActionsClient()).toThrowErrorMatchingInlineSnapshot( `"Unable to create actions client because the Encrypted Saved Objects plugin uses an ephemeral encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command."` ); diff --git a/x-pack/plugins/actions/server/plugin.ts b/x-pack/plugins/actions/server/plugin.ts index 133e5f9c6aa2c..1543f8d7a07ce 100644 --- a/x-pack/plugins/actions/server/plugin.ts +++ b/x-pack/plugins/actions/server/plugin.ts @@ -14,7 +14,6 @@ import { CoreStart, KibanaRequest, Logger, - RequestHandler, IContextProvider, ElasticsearchServiceStart, ILegacyClusterClient, @@ -46,6 +45,7 @@ import { ActionTypeConfig, ActionTypeSecrets, ActionTypeParams, + ActionsRequestHandlerContext, } from './types'; import { getActionsConfigurationUtilities } from './actions_config'; @@ -228,7 +228,7 @@ export class ActionsPlugin implements Plugin, Plugi } this.kibanaIndexConfig.subscribe((config) => { - core.http.registerRouteHandlerContext( + core.http.registerRouteHandlerContext( 'actions', this.createRouteHandlerContext(core, config.kibana.index) ); @@ -243,7 +243,7 @@ export class ActionsPlugin implements Plugin, Plugi }); // Routes - const router = core.http.createRouter(); + const router = core.http.createRouter(); createActionRoute(router, this.licenseState); deleteActionRoute(router, this.licenseState); getActionRoute(router, this.licenseState); @@ -448,7 +448,7 @@ export class ActionsPlugin implements Plugin, Plugi private createRouteHandlerContext = ( core: CoreSetup, defaultKibanaIndex: string - ): IContextProvider, 'actions'> => { + ): IContextProvider => { const { actionTypeRegistry, isESOUsingEphemeralEncryptionKey, diff --git a/x-pack/plugins/actions/server/routes/create.ts b/x-pack/plugins/actions/server/routes/create.ts index 462d3f42b506c..3400568c7dc4c 100644 --- a/x-pack/plugins/actions/server/routes/create.ts +++ b/x-pack/plugins/actions/server/routes/create.ts @@ -4,15 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; -import { ActionResult } from '../types'; +import { schema } from '@kbn/config-schema'; +import { IRouter } from 'kibana/server'; +import { ActionResult, ActionsRequestHandlerContext } from '../types'; import { ILicenseState, verifyApiAccess, isErrorThatHandlesItsOwnResponse } from '../lib'; import { BASE_ACTION_API_PATH } from '../../common'; @@ -23,7 +17,10 @@ export const bodySchema = schema.object({ secrets: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }), }); -export const createActionRoute = (router: IRouter, licenseState: ILicenseState) => { +export const createActionRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.post( { path: `${BASE_ACTION_API_PATH}/action`, @@ -31,11 +28,7 @@ export const createActionRoute = (router: IRouter, licenseState: ILicenseState) body: bodySchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { diff --git a/x-pack/plugins/actions/server/routes/delete.ts b/x-pack/plugins/actions/server/routes/delete.ts index a7303247e95b0..7183ebb7c8233 100644 --- a/x-pack/plugins/actions/server/routes/delete.ts +++ b/x-pack/plugins/actions/server/routes/delete.ts @@ -9,22 +9,20 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import { IRouter } from 'kibana/server'; import { ILicenseState, verifyApiAccess, isErrorThatHandlesItsOwnResponse } from '../lib'; import { BASE_ACTION_API_PATH } from '../../common'; +import { ActionsRequestHandlerContext } from '../types'; const paramSchema = schema.object({ id: schema.string(), }); -export const deleteActionRoute = (router: IRouter, licenseState: ILicenseState) => { +export const deleteActionRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.delete( { path: `${BASE_ACTION_API_PATH}/action/{id}`, @@ -32,11 +30,7 @@ export const deleteActionRoute = (router: IRouter, licenseState: ILicenseState) params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' }); diff --git a/x-pack/plugins/actions/server/routes/execute.ts b/x-pack/plugins/actions/server/routes/execute.ts index 8191b6946d332..b2398a8b366e6 100644 --- a/x-pack/plugins/actions/server/routes/execute.ts +++ b/x-pack/plugins/actions/server/routes/execute.ts @@ -3,17 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import { IRouter } from 'kibana/server'; import { ILicenseState, verifyApiAccess, isErrorThatHandlesItsOwnResponse } from '../lib'; -import { ActionTypeExecutorResult } from '../types'; +import { ActionTypeExecutorResult, ActionsRequestHandlerContext } from '../types'; import { BASE_ACTION_API_PATH } from '../../common'; import { asHttpRequestExecutionSource } from '../lib/action_execution_source'; @@ -25,7 +19,10 @@ const bodySchema = schema.object({ params: schema.recordOf(schema.string(), schema.any()), }); -export const executeActionRoute = (router: IRouter, licenseState: ILicenseState) => { +export const executeActionRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.post( { path: `${BASE_ACTION_API_PATH}/action/{id}/_execute`, @@ -34,11 +31,7 @@ export const executeActionRoute = (router: IRouter, licenseState: ILicenseState) params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, TypeOf>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { diff --git a/x-pack/plugins/actions/server/routes/get.ts b/x-pack/plugins/actions/server/routes/get.ts index 33577fad87c04..401fa93bebd80 100644 --- a/x-pack/plugins/actions/server/routes/get.ts +++ b/x-pack/plugins/actions/server/routes/get.ts @@ -4,22 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import { IRouter } from 'kibana/server'; import { ILicenseState, verifyApiAccess } from '../lib'; import { BASE_ACTION_API_PATH } from '../../common'; +import { ActionsRequestHandlerContext } from '../types'; const paramSchema = schema.object({ id: schema.string(), }); -export const getActionRoute = (router: IRouter, licenseState: ILicenseState) => { +export const getActionRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.get( { path: `${BASE_ACTION_API_PATH}/action/{id}`, @@ -27,11 +25,7 @@ export const getActionRoute = (router: IRouter, licenseState: ILicenseState) => params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' }); diff --git a/x-pack/plugins/actions/server/routes/get_all.ts b/x-pack/plugins/actions/server/routes/get_all.ts index 1b57f31d14a0d..fa3bd20858b0d 100644 --- a/x-pack/plugins/actions/server/routes/get_all.ts +++ b/x-pack/plugins/actions/server/routes/get_all.ts @@ -4,27 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { IRouter } from 'kibana/server'; import { ILicenseState, verifyApiAccess } from '../lib'; import { BASE_ACTION_API_PATH } from '../../common'; +import { ActionsRequestHandlerContext } from '../types'; -export const getAllActionRoute = (router: IRouter, licenseState: ILicenseState) => { +export const getAllActionRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.get( { path: `${BASE_ACTION_API_PATH}`, validate: {}, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' }); diff --git a/x-pack/plugins/actions/server/routes/list_action_types.ts b/x-pack/plugins/actions/server/routes/list_action_types.ts index c960a6bac6de0..b84eede91306e 100644 --- a/x-pack/plugins/actions/server/routes/list_action_types.ts +++ b/x-pack/plugins/actions/server/routes/list_action_types.ts @@ -4,27 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { IRouter } from 'kibana/server'; import { ILicenseState, verifyApiAccess } from '../lib'; import { BASE_ACTION_API_PATH } from '../../common'; +import { ActionsRequestHandlerContext } from '../types'; -export const listActionTypesRoute = (router: IRouter, licenseState: ILicenseState) => { +export const listActionTypesRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.get( { path: `${BASE_ACTION_API_PATH}/list_action_types`, validate: {}, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' }); diff --git a/x-pack/plugins/actions/server/routes/update.ts b/x-pack/plugins/actions/server/routes/update.ts index 328ce74ef0b08..215d617d270b8 100644 --- a/x-pack/plugins/actions/server/routes/update.ts +++ b/x-pack/plugins/actions/server/routes/update.ts @@ -4,16 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import { IRouter } from 'kibana/server'; import { ILicenseState, verifyApiAccess, isErrorThatHandlesItsOwnResponse } from '../lib'; import { BASE_ACTION_API_PATH } from '../../common'; +import { ActionsRequestHandlerContext } from '../types'; const paramSchema = schema.object({ id: schema.string(), @@ -25,7 +20,10 @@ const bodySchema = schema.object({ secrets: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }), }); -export const updateActionRoute = (router: IRouter, licenseState: ILicenseState) => { +export const updateActionRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { router.put( { path: `${BASE_ACTION_API_PATH}/action/{id}`, @@ -34,11 +32,7 @@ export const updateActionRoute = (router: IRouter, licenseState: ILicenseState) params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, TypeOf>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.actions) { return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' }); diff --git a/x-pack/plugins/actions/server/types.ts b/x-pack/plugins/actions/server/types.ts index 81d6c3550a53c..f545c0fc96633 100644 --- a/x-pack/plugins/actions/server/types.ts +++ b/x-pack/plugins/actions/server/types.ts @@ -15,6 +15,7 @@ import { SavedObjectsClientContract, SavedObjectAttributes, ElasticsearchClient, + RequestHandlerContext, } from '../../../../src/core/server'; import { ActionTypeExecutorResult } from '../common'; export { ActionTypeExecutorResult } from '../common'; @@ -40,13 +41,13 @@ export interface Services { getLegacyScopedClusterClient(clusterClient: ILegacyClusterClient): ILegacyScopedClusterClient; } -declare module 'src/core/server' { - interface RequestHandlerContext { - actions?: { - getActionsClient: () => ActionsClient; - listTypes: ActionTypeRegistry['list']; - }; - } +export interface ActionsApiRequestHandlerContext { + getActionsClient: () => ActionsClient; + listTypes: ActionTypeRegistry['list']; +} + +export interface ActionsRequestHandlerContext extends RequestHandlerContext { + actions: ActionsApiRequestHandlerContext; } export interface ActionsPlugin { diff --git a/x-pack/plugins/alerts/server/index.ts b/x-pack/plugins/alerts/server/index.ts index da56da671f9b0..50698b840f9c7 100644 --- a/x-pack/plugins/alerts/server/index.ts +++ b/x-pack/plugins/alerts/server/index.ts @@ -12,7 +12,7 @@ import { AlertsConfigType } from './types'; export type AlertsClient = PublicMethodsOf; -export { +export type { ActionVariable, AlertType, ActionGroup, @@ -26,6 +26,7 @@ export { PartialAlert, AlertInstanceState, AlertInstanceContext, + AlertingApiRequestHandlerContext, } from './types'; export { PluginSetupContract, PluginStartContract } from './plugin'; export { FindResult } from './alerts_client'; diff --git a/x-pack/plugins/alerts/server/plugin.ts b/x-pack/plugins/alerts/server/plugin.ts index cb165fa56d046..fc76b2383b5bd 100644 --- a/x-pack/plugins/alerts/server/plugin.ts +++ b/x-pack/plugins/alerts/server/plugin.ts @@ -28,13 +28,13 @@ import { CoreStart, SavedObjectsServiceStart, IContextProvider, - RequestHandler, ElasticsearchServiceStart, ILegacyClusterClient, StatusServiceSetup, ServiceStatus, SavedObjectsBulkGetObject, } from '../../../../src/core/server'; +import type { AlertingRequestHandlerContext } from './types'; import { aggregateAlertRoute, @@ -255,10 +255,13 @@ export class AlertingPlugin { initializeAlertingHealth(this.logger, plugins.taskManager, core.getStartServices()); - core.http.registerRouteHandlerContext('alerting', this.createRouteHandlerContext(core)); + core.http.registerRouteHandlerContext( + 'alerting', + this.createRouteHandlerContext(core) + ); // Routes - const router = core.http.createRouter(); + const router = core.http.createRouter(); // Register routes aggregateAlertRoute(router, this.licenseState); createAlertRoute(router, this.licenseState); @@ -392,7 +395,7 @@ export class AlertingPlugin { private createRouteHandlerContext = ( core: CoreSetup - ): IContextProvider, 'alerting'> => { + ): IContextProvider => { const { alertTypeRegistry, alertsClientFactory } = this; return async function alertsRouteHandlerContext(context, request) { const [{ savedObjects }] = await core.getStartServices(); diff --git a/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts b/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts index b3f407b20c142..9883d5ec0dd5f 100644 --- a/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts +++ b/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts @@ -4,18 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - RequestHandlerContext, - KibanaRequest, - KibanaResponseFactory, - ILegacyClusterClient, -} from 'kibana/server'; +import { KibanaRequest, KibanaResponseFactory, ILegacyClusterClient } from 'kibana/server'; import { identity } from 'lodash'; import type { MethodKeysOf } from '@kbn/utility-types'; import { httpServerMock } from '../../../../../src/core/server/mocks'; import { alertsClientMock, AlertsClientMock } from '../alerts_client.mock'; import { AlertsHealth, AlertType } from '../../common'; import { elasticsearchServiceMock } from '../../../../../src/core/server/mocks'; +import type { AlertingRequestHandlerContext } from '../types'; export function mockHandlerArguments( { @@ -32,7 +28,11 @@ export function mockHandlerArguments( }, req: unknown, res?: Array> -): [RequestHandlerContext, KibanaRequest, KibanaResponseFactory] { +): [ + AlertingRequestHandlerContext, + KibanaRequest, + KibanaResponseFactory +] { const listTypes = jest.fn(() => listTypesRes); return [ ({ @@ -44,7 +44,7 @@ export function mockHandlerArguments( }, getFrameworkHealth, }, - } as unknown) as RequestHandlerContext, + } as unknown) as AlertingRequestHandlerContext, req as KibanaRequest, mockResponseFactory(res), ]; diff --git a/x-pack/plugins/alerts/server/routes/aggregate.ts b/x-pack/plugins/alerts/server/routes/aggregate.ts index 0fcfb6f6147e7..3b809196f9b70 100644 --- a/x-pack/plugins/alerts/server/routes/aggregate.ts +++ b/x-pack/plugins/alerts/server/routes/aggregate.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -38,7 +32,7 @@ const querySchema = schema.object({ filter: schema.maybe(schema.string()), }); -export const aggregateAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const aggregateAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.get( { path: `${BASE_ALERT_API_PATH}/_aggregate`, @@ -46,11 +40,7 @@ export const aggregateAlertRoute = (router: IRouter, licenseState: ILicenseState query: querySchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/create.ts b/x-pack/plugins/alerts/server/routes/create.ts index a79a9d40b236f..2b6735d9063df 100644 --- a/x-pack/plugins/alerts/server/routes/create.ts +++ b/x-pack/plugins/alerts/server/routes/create.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { validateDurationSchema } from '../lib'; @@ -48,7 +42,7 @@ export const bodySchema = schema.object({ notifyWhen: schema.nullable(schema.string({ validate: validateNotifyWhenType })), }); -export const createAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const createAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert`, @@ -57,11 +51,7 @@ export const createAlertRoute = (router: IRouter, licenseState: ILicenseState) = }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { diff --git a/x-pack/plugins/alerts/server/routes/delete.ts b/x-pack/plugins/alerts/server/routes/delete.ts index 3ac975d3a1546..12991e28d67ce 100644 --- a/x-pack/plugins/alerts/server/routes/delete.ts +++ b/x-pack/plugins/alerts/server/routes/delete.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -20,7 +14,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const deleteAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const deleteAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.delete( { path: `${BASE_ALERT_API_PATH}/alert/{id}`, @@ -28,11 +22,7 @@ export const deleteAlertRoute = (router: IRouter, licenseState: ILicenseState) = params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/disable.ts b/x-pack/plugins/alerts/server/routes/disable.ts index e96cb397f554b..91663bd852879 100644 --- a/x-pack/plugins/alerts/server/routes/disable.ts +++ b/x-pack/plugins/alerts/server/routes/disable.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -21,7 +15,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const disableAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const disableAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{id}/_disable`, @@ -29,11 +23,7 @@ export const disableAlertRoute = (router: IRouter, licenseState: ILicenseState) params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/enable.ts b/x-pack/plugins/alerts/server/routes/enable.ts index 81c5027c7587b..cbfcbc44d9f5f 100644 --- a/x-pack/plugins/alerts/server/routes/enable.ts +++ b/x-pack/plugins/alerts/server/routes/enable.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -22,7 +16,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const enableAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const enableAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{id}/_enable`, @@ -31,11 +25,7 @@ export const enableAlertRoute = (router: IRouter, licenseState: ILicenseState) = }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/find.ts b/x-pack/plugins/alerts/server/routes/find.ts index 487ff571187f4..195abf0a15a9f 100644 --- a/x-pack/plugins/alerts/server/routes/find.ts +++ b/x-pack/plugins/alerts/server/routes/find.ts @@ -4,14 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; + import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -43,7 +38,7 @@ const querySchema = schema.object({ filter: schema.maybe(schema.string()), }); -export const findAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const findAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.get( { path: `${BASE_ALERT_API_PATH}/_find`, @@ -51,11 +46,7 @@ export const findAlertRoute = (router: IRouter, licenseState: ILicenseState) => query: querySchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/get.ts b/x-pack/plugins/alerts/server/routes/get.ts index ae592f37cd55c..ddf16d1022c89 100644 --- a/x-pack/plugins/alerts/server/routes/get.ts +++ b/x-pack/plugins/alerts/server/routes/get.ts @@ -4,23 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; +import type { AlertingRouter } from '../types'; const paramSchema = schema.object({ id: schema.string(), }); -export const getAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const getAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.get( { path: `${BASE_ALERT_API_PATH}/alert/{id}`, @@ -28,11 +22,7 @@ export const getAlertRoute = (router: IRouter, licenseState: ILicenseState) => { params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/get_alert_instance_summary.ts b/x-pack/plugins/alerts/server/routes/get_alert_instance_summary.ts index 33f331f7dce02..095b8e492467c 100644 --- a/x-pack/plugins/alerts/server/routes/get_alert_instance_summary.ts +++ b/x-pack/plugins/alerts/server/routes/get_alert_instance_summary.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -24,7 +18,10 @@ const querySchema = schema.object({ dateStart: schema.maybe(schema.string()), }); -export const getAlertInstanceSummaryRoute = (router: IRouter, licenseState: ILicenseState) => { +export const getAlertInstanceSummaryRoute = ( + router: AlertingRouter, + licenseState: ILicenseState +) => { router.get( { path: `${BASE_ALERT_API_PATH}/alert/{id}/_instance_summary`, @@ -33,11 +30,7 @@ export const getAlertInstanceSummaryRoute = (router: IRouter, licenseState: ILic query: querySchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, TypeOf, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/get_alert_state.ts b/x-pack/plugins/alerts/server/routes/get_alert_state.ts index 52ad8f9f31874..e818e5d04304d 100644 --- a/x-pack/plugins/alerts/server/routes/get_alert_state.ts +++ b/x-pack/plugins/alerts/server/routes/get_alert_state.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -20,7 +14,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const getAlertStateRoute = (router: IRouter, licenseState: ILicenseState) => { +export const getAlertStateRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.get( { path: `${BASE_ALERT_API_PATH}/alert/{id}/state`, @@ -28,11 +22,7 @@ export const getAlertStateRoute = (router: IRouter, licenseState: ILicenseState) params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/health.ts b/x-pack/plugins/alerts/server/routes/health.ts index 962ad7e1bb29a..b21f389e3b088 100644 --- a/x-pack/plugins/alerts/server/routes/health.ts +++ b/x-pack/plugins/alerts/server/routes/health.ts @@ -4,13 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { AlertingFrameworkHealth } from '../types'; @@ -28,7 +22,7 @@ interface XPackUsageSecurity { } export function healthRoute( - router: IRouter, + router: AlertingRouter, licenseState: ILicenseState, encryptedSavedObjects: EncryptedSavedObjectsPluginSetup ) { @@ -37,11 +31,7 @@ export function healthRoute( path: '/api/alerts/_health', validate: false, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/lib/error_handler.ts b/x-pack/plugins/alerts/server/routes/lib/error_handler.ts index e0c620b0670c9..f0ee9087cbe8f 100644 --- a/x-pack/plugins/alerts/server/routes/lib/error_handler.ts +++ b/x-pack/plugins/alerts/server/routes/lib/error_handler.ts @@ -5,22 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { - RequestHandler, - KibanaRequest, - KibanaResponseFactory, - RequestHandlerContext, - RouteMethod, -} from 'kibana/server'; +import { RequestHandlerWrapper } from 'kibana/server'; -export function handleDisabledApiKeysError( - handler: RequestHandler -): RequestHandler { - return async ( - context: RequestHandlerContext, - request: KibanaRequest, - response: KibanaResponseFactory - ) => { +export const handleDisabledApiKeysError: RequestHandlerWrapper = (handler) => { + return async (context, request, response) => { try { return await handler(context, request, response); } catch (e) { @@ -36,7 +24,7 @@ export function handleDisabledApiKeysError( throw e; } }; -} +}; export function isApiKeyDisabledError(e: Error) { return e?.message?.includes('api keys are not enabled') ?? false; diff --git a/x-pack/plugins/alerts/server/routes/list_alert_types.ts b/x-pack/plugins/alerts/server/routes/list_alert_types.ts index 9b4b352e211f1..b5cefccfd4b0d 100644 --- a/x-pack/plugins/alerts/server/routes/list_alert_types.ts +++ b/x-pack/plugins/alerts/server/routes/list_alert_types.ts @@ -4,28 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; -export const listAlertTypesRoute = (router: IRouter, licenseState: ILicenseState) => { +export const listAlertTypesRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.get( { path: `${BASE_ALERT_API_PATH}/list_alert_types`, validate: {}, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/mute_all.ts b/x-pack/plugins/alerts/server/routes/mute_all.ts index 224216961bb7f..92127a7cec676 100644 --- a/x-pack/plugins/alerts/server/routes/mute_all.ts +++ b/x-pack/plugins/alerts/server/routes/mute_all.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -21,7 +15,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const muteAllAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const muteAllAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{id}/_mute_all`, @@ -29,11 +23,7 @@ export const muteAllAlertRoute = (router: IRouter, licenseState: ILicenseState) params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/mute_instance.ts b/x-pack/plugins/alerts/server/routes/mute_instance.ts index b374866177231..923bce5b8c316 100644 --- a/x-pack/plugins/alerts/server/routes/mute_instance.ts +++ b/x-pack/plugins/alerts/server/routes/mute_instance.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -24,7 +18,7 @@ const paramSchema = schema.object({ alert_instance_id: schema.string(), }); -export const muteAlertInstanceRoute = (router: IRouter, licenseState: ILicenseState) => { +export const muteAlertInstanceRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{alert_id}/alert_instance/{alert_instance_id}/_mute`, @@ -32,11 +26,7 @@ export const muteAlertInstanceRoute = (router: IRouter, licenseState: ILicenseSt params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/unmute_all.ts b/x-pack/plugins/alerts/server/routes/unmute_all.ts index e249ec7ffa58f..8709cf3ae887e 100644 --- a/x-pack/plugins/alerts/server/routes/unmute_all.ts +++ b/x-pack/plugins/alerts/server/routes/unmute_all.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -21,7 +15,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const unmuteAllAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const unmuteAllAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{id}/_unmute_all`, @@ -29,11 +23,7 @@ export const unmuteAllAlertRoute = (router: IRouter, licenseState: ILicenseState params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/unmute_instance.ts b/x-pack/plugins/alerts/server/routes/unmute_instance.ts index bcab6e21578aa..d1c62ce365920 100644 --- a/x-pack/plugins/alerts/server/routes/unmute_instance.ts +++ b/x-pack/plugins/alerts/server/routes/unmute_instance.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -22,7 +16,7 @@ const paramSchema = schema.object({ alertInstanceId: schema.string(), }); -export const unmuteAlertInstanceRoute = (router: IRouter, licenseState: ILicenseState) => { +export const unmuteAlertInstanceRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{alertId}/alert_instance/{alertInstanceId}/_unmute`, @@ -30,11 +24,7 @@ export const unmuteAlertInstanceRoute = (router: IRouter, licenseState: ILicense params: paramSchema, }, }, - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/update.ts b/x-pack/plugins/alerts/server/routes/update.ts index d3ecc9eb3e381..2e70843dcb142 100644 --- a/x-pack/plugins/alerts/server/routes/update.ts +++ b/x-pack/plugins/alerts/server/routes/update.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { validateDurationSchema } from '../lib'; @@ -43,7 +37,7 @@ const bodySchema = schema.object({ notifyWhen: schema.nullable(schema.string({ validate: validateNotifyWhenType })), }); -export const updateAlertRoute = (router: IRouter, licenseState: ILicenseState) => { +export const updateAlertRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.put( { path: `${BASE_ALERT_API_PATH}/alert/{id}`, @@ -53,11 +47,7 @@ export const updateAlertRoute = (router: IRouter, licenseState: ILicenseState) = }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, TypeOf>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/routes/update_api_key.ts b/x-pack/plugins/alerts/server/routes/update_api_key.ts index fb7639d975980..743435c96e6ab 100644 --- a/x-pack/plugins/alerts/server/routes/update_api_key.ts +++ b/x-pack/plugins/alerts/server/routes/update_api_key.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, - KibanaRequest, - IKibanaResponse, - KibanaResponseFactory, -} from 'kibana/server'; +import { schema } from '@kbn/config-schema'; +import type { AlertingRouter } from '../types'; import { ILicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; @@ -22,7 +16,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const updateApiKeyRoute = (router: IRouter, licenseState: ILicenseState) => { +export const updateApiKeyRoute = (router: AlertingRouter, licenseState: ILicenseState) => { router.post( { path: `${BASE_ALERT_API_PATH}/alert/{id}/_update_api_key`, @@ -31,11 +25,7 @@ export const updateApiKeyRoute = (router: IRouter, licenseState: ILicenseState) }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function ( - context: RequestHandlerContext, - req: KibanaRequest, unknown, unknown>, - res: KibanaResponseFactory - ): Promise { + router.handleLegacyErrors(async function (context, req, res) { verifyApiAccess(licenseState); if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); diff --git a/x-pack/plugins/alerts/server/types.ts b/x-pack/plugins/alerts/server/types.ts index 39c52d9653aaa..0e686bc1f21d7 100644 --- a/x-pack/plugins/alerts/server/types.ts +++ b/x-pack/plugins/alerts/server/types.ts @@ -3,6 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import type { IRouter, RequestHandlerContext } from 'src/core/server'; import type { PublicMethodsOf } from '@kbn/utility-types'; import { PublicAlertInstance } from './alert_instance'; import { AlertTypeRegistry as OrigAlertTypeRegistry } from './alert_type_registry'; @@ -37,16 +38,27 @@ export type WithoutQueryAndParams = Pick Services; export type SpaceIdToNamespaceFunction = (spaceId?: string) => string | undefined; -declare module 'src/core/server' { - interface RequestHandlerContext { - alerting?: { - getAlertsClient: () => AlertsClient; - listTypes: AlertTypeRegistry['list']; - getFrameworkHealth: () => Promise; - }; - } +/** + * @public + */ +export interface AlertingApiRequestHandlerContext { + getAlertsClient: () => AlertsClient; + listTypes: AlertTypeRegistry['list']; + getFrameworkHealth: () => Promise; +} + +/** + * @internal + */ +export interface AlertingRequestHandlerContext extends RequestHandlerContext { + alerting: AlertingApiRequestHandlerContext; } +/** + * @internal + */ +export type AlertingRouter = IRouter; + export interface Services { /** * @deprecated Use `scopedClusterClient` instead. diff --git a/x-pack/plugins/apm/server/feature.ts b/x-pack/plugins/apm/server/feature.ts index 9eba18d44ad50..deb89314fc626 100644 --- a/x-pack/plugins/apm/server/feature.ts +++ b/x-pack/plugins/apm/server/feature.ts @@ -10,7 +10,7 @@ import { AlertType } from '../common/alert_types'; import { DEFAULT_APP_CATEGORIES } from '../../../../src/core/server'; import { LicensingPluginSetup, - LicensingRequestHandlerContext, + LicensingApiRequestHandlerContext, } from '../../licensing/server'; export const APM_FEATURE = { @@ -97,7 +97,7 @@ export function notifyFeatureUsage({ licensingPlugin, featureName, }: { - licensingPlugin: LicensingRequestHandlerContext; + licensingPlugin: LicensingApiRequestHandlerContext; featureName: FeatureName; }) { const feature = features[featureName]; diff --git a/x-pack/plugins/apm/server/plugin.ts b/x-pack/plugins/apm/server/plugin.ts index 44269b1775953..09b75137e12df 100644 --- a/x-pack/plugins/apm/server/plugin.ts +++ b/x-pack/plugins/apm/server/plugin.ts @@ -14,7 +14,6 @@ import { Logger, Plugin, PluginInitializerContext, - RequestHandlerContext, } from 'src/core/server'; import { APMConfig, APMXPackConfig, mergeConfigs } from '.'; import { APMOSSPluginSetup } from '../../../../src/plugins/apm_oss/server'; @@ -42,6 +41,7 @@ import { createApmApi } from './routes/create_apm_api'; import { apmIndices, apmTelemetry } from './saved_objects'; import { createElasticCloudInstructions } from './tutorial/elastic_cloud'; import { uiSettings } from './ui_settings'; +import type { ApmPluginRequestHandlerContext } from './routes/typings'; export interface APMPluginSetup { config$: Observable; @@ -49,7 +49,7 @@ export interface APMPluginSetup { createApmEventClient: (params: { debug?: boolean; request: KibanaRequest; - context: RequestHandlerContext; + context: ApmPluginRequestHandlerContext; }) => Promise>; } @@ -166,7 +166,7 @@ export class APMPlugin implements Plugin { }: { debug?: boolean; request: KibanaRequest; - context: RequestHandlerContext; + context: ApmPluginRequestHandlerContext; }) => { const [indices, includeFrozen] = await Promise.all([ boundGetApmIndices(), diff --git a/x-pack/plugins/apm/server/routes/create_api/index.ts b/x-pack/plugins/apm/server/routes/create_api/index.ts index 94711cf76c145..cfb31670bd521 100644 --- a/x-pack/plugins/apm/server/routes/create_api/index.ts +++ b/x-pack/plugins/apm/server/routes/create_api/index.ts @@ -15,6 +15,7 @@ import { strictKeysRt } from '../../../common/runtime_types/strict_keys_rt'; import { APMConfig } from '../..'; import { ServerAPI } from '../typings'; import { jsonRt } from '../../../common/runtime_types/json_rt'; +import type { ApmPluginRequestHandlerContext } from '../typings'; const debugRt = t.exact( t.partial({ @@ -73,7 +74,10 @@ export function createApi() { const anyObject = schema.object({}, { unknowns: 'allow' }); - (router[typedRouterMethod] as RouteRegistrar)( + (router[typedRouterMethod] as RouteRegistrar< + typeof typedRouterMethod, + ApmPluginRequestHandlerContext + >)( { path, options, diff --git a/x-pack/plugins/apm/server/routes/typings.ts b/x-pack/plugins/apm/server/routes/typings.ts index 81b25e572a28d..7d7a5c3b0dab3 100644 --- a/x-pack/plugins/apm/server/routes/typings.ts +++ b/x-pack/plugins/apm/server/routes/typings.ts @@ -14,6 +14,7 @@ import { import { Observable } from 'rxjs'; import { RequiredKeys } from 'utility-types'; import { ObservabilityPluginSetup } from '../../../observability/server'; +import { LicensingApiRequestHandlerContext } from '../../../licensing/server'; import { SecurityPluginSetup } from '../../../security/server'; import { MlPluginSetup } from '../../../ml/server'; import { FetchOptions } from '../../common/fetch_options'; @@ -64,9 +65,16 @@ export interface Route< handler: RouteHandler; } +/** + * @internal + */ +export interface ApmPluginRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; +} + export type APMRequestHandlerContext< TRouteParams = {} -> = RequestHandlerContext & { +> = ApmPluginRequestHandlerContext & { params: TRouteParams & { query: { _debug: boolean } }; config: APMConfig; logger: Logger; diff --git a/x-pack/plugins/beats_management/server/lib/types.ts b/x-pack/plugins/beats_management/server/lib/types.ts index d86aa8652fdbc..20467af7018f7 100644 --- a/x-pack/plugins/beats_management/server/lib/types.ts +++ b/x-pack/plugins/beats_management/server/lib/types.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import type { IRouter, RequestHandlerContext } from 'src/core/server'; import { DatabaseAdapter } from './adapters/database/adapter_types'; import { FrameworkUser } from './adapters/framework/adapter_types'; import { BeatEventsLib } from './beat_events'; @@ -40,3 +40,20 @@ export interface AsyncResponse { export interface AsyncResponse { data: DataType; } + +/** + * @internal + */ +export type BeatsManagementApiRequestHandlerContext = CMServerLibs; + +/** + * @internal + */ +export interface BeatsManagementRequestHandlerContext extends RequestHandlerContext { + beatsManagement: CMServerLibs; +} + +/** + * @internal + */ +export type BeatsManagementRouter = IRouter; diff --git a/x-pack/plugins/beats_management/server/plugin.ts b/x-pack/plugins/beats_management/server/plugin.ts index fde0a2efecdda..d52de39ed458f 100644 --- a/x-pack/plugins/beats_management/server/plugin.ts +++ b/x-pack/plugins/beats_management/server/plugin.ts @@ -5,17 +5,12 @@ */ import { take } from 'rxjs/operators'; -import { - CoreSetup, - CoreStart, - Plugin, - PluginInitializerContext, -} from '../../../../src/core/server'; +import { CoreSetup, CoreStart, Plugin, PluginInitializerContext } from 'src/core/server'; import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; import { SecurityPluginSetup } from '../../security/server'; import { LicensingPluginStart } from '../../licensing/server'; import { BeatsManagementConfigType } from '../common'; -import { CMServerLibs } from './lib/types'; +import type { BeatsManagementRequestHandlerContext, CMServerLibs } from './lib/types'; import { registerRoutes } from './routes'; import { compose } from './lib/compose/kibana'; import { INDEX_NAMES } from '../common/constants'; @@ -30,12 +25,6 @@ interface StartDeps { licensing: LicensingPluginStart; } -declare module 'src/core/server' { - interface RequestHandlerContext { - beatsManagement?: CMServerLibs; - } -} - export class BeatsManagementPlugin implements Plugin<{}, {}, SetupDeps, StartDeps> { private securitySetup?: SecurityPluginSetup; private beatsLibs?: CMServerLibs; @@ -47,12 +36,15 @@ export class BeatsManagementPlugin implements Plugin<{}, {}, SetupDeps, StartDep public async setup(core: CoreSetup, { features, security }: SetupDeps) { this.securitySetup = security; - const router = core.http.createRouter(); + const router = core.http.createRouter(); registerRoutes(router); - core.http.registerRouteHandlerContext('beatsManagement', (_, req) => { - return this.beatsLibs!; - }); + core.http.registerRouteHandlerContext( + 'beatsManagement', + (_, req) => { + return this.beatsLibs!; + } + ); features.registerElasticsearchFeature({ id: 'beats_management', diff --git a/x-pack/plugins/beats_management/server/routes/beats/configuration.ts b/x-pack/plugins/beats_management/server/routes/beats/configuration.ts index 1496e4bbfc99f..363b8e3f07163 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/configuration.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/configuration.ts @@ -5,12 +5,12 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { ConfigurationBlock } from '../../../common/domain_types'; import { ReturnTypeList } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerGetBeatConfigurationRoute = (router: IRouter) => { +export const registerGetBeatConfigurationRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/agent/{beatId}/configuration', diff --git a/x-pack/plugins/beats_management/server/routes/beats/enroll.ts b/x-pack/plugins/beats_management/server/routes/beats/enroll.ts index be8fff3b7c437..919d52942cd62 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/enroll.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/enroll.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { ensureRawRequest } from '../../../../../../src/core/server/http/router'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { BeatEnrollmentStatus } from '../../lib/types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerBeatEnrollmentRoute = (router: IRouter) => { +export const registerBeatEnrollmentRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file https://github.com/elastic/kibana/issues/26024 router.post( { diff --git a/x-pack/plugins/beats_management/server/routes/beats/events.ts b/x-pack/plugins/beats_management/server/routes/beats/events.ts index b87e6d684228a..c8e66c6d745d0 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/events.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/events.ts @@ -5,11 +5,11 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { ReturnTypeBulkAction } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerBeatEventsRoute = (router: IRouter) => { +export const registerBeatEventsRoute = (router: BeatsManagementRouter) => { router.post( { path: '/api/beats/{beatId}/events', diff --git a/x-pack/plugins/beats_management/server/routes/beats/get.ts b/x-pack/plugins/beats_management/server/routes/beats/get.ts index 8762f325e7484..8e2279c7b9c21 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/get.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/get.ts @@ -5,12 +5,12 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { CMBeat } from '../../../common/domain_types'; import { ReturnTypeGet } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerGetBeatRoute = (router: IRouter) => { +export const registerGetBeatRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/agent/{beatId}/{token?}', diff --git a/x-pack/plugins/beats_management/server/routes/beats/list.ts b/x-pack/plugins/beats_management/server/routes/beats/list.ts index e4108238e3f2f..1ae77134f2b22 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/list.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/list.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { CMBeat } from '../../../common/domain_types'; import { ReturnTypeList } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerListAgentsRoute = (router: IRouter) => { +export const registerListAgentsRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/agents/{listByAndValue*}', @@ -33,7 +33,7 @@ export const registerListAgentsRoute = (router: IRouter) => { requiredLicense: REQUIRED_LICENSES, }, async (context, request, response) => { - const beatsManagement = context.beatsManagement!; + const beatsManagement = context.beatsManagement; const user = beatsManagement.framework.getUser(request); const listByAndValueParts = request.params.listByAndValue?.split('/') ?? []; diff --git a/x-pack/plugins/beats_management/server/routes/beats/tag_assignment.ts b/x-pack/plugins/beats_management/server/routes/beats/tag_assignment.ts index 0397f8ec4398e..12205747ed566 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/tag_assignment.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/tag_assignment.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { ReturnTypeBulkAction } from '../../../common/return_types'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import type { BeatsTagAssignment } from '../../../public/lib/adapters/beats/adapter_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerTagAssignmentsRoute = (router: IRouter) => { +export const registerTagAssignmentsRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file https://github.com/elastic/kibana/issues/26024 router.post( { diff --git a/x-pack/plugins/beats_management/server/routes/beats/tag_removal.ts b/x-pack/plugins/beats_management/server/routes/beats/tag_removal.ts index a04ed81fb183b..195810d6bf3e4 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/tag_removal.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/tag_removal.ts @@ -5,12 +5,12 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { ReturnTypeBulkAction } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerTagRemovalsRoute = (router: IRouter) => { +export const registerTagRemovalsRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file https://github.com/elastic/kibana/issues/26024 router.post( { @@ -33,7 +33,7 @@ export const registerTagRemovalsRoute = (router: IRouter) => { requiredRoles: ['beats_admin'], }, async (context, request, response) => { - const beatsManagement = context.beatsManagement!; + const beatsManagement = context.beatsManagement; const user = beatsManagement.framework.getUser(request); const { removals } = request.body; diff --git a/x-pack/plugins/beats_management/server/routes/beats/update.ts b/x-pack/plugins/beats_management/server/routes/beats/update.ts index 21bd6555b28dd..1e9c2db025578 100644 --- a/x-pack/plugins/beats_management/server/routes/beats/update.ts +++ b/x-pack/plugins/beats_management/server/routes/beats/update.ts @@ -5,7 +5,7 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { ensureRawRequest } from '../../../../../../src/core/server/http/router'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; @@ -14,7 +14,7 @@ import { ReturnTypeUpdate } from '../../../common/return_types'; import { internalUser } from '../../lib/adapters/framework/adapter_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerBeatUpdateRoute = (router: IRouter) => { +export const registerBeatUpdateRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file (include who did the verification as well) https://github.com/elastic/kibana/issues/26024 router.put( { @@ -44,7 +44,7 @@ export const registerBeatUpdateRoute = (router: IRouter) => { requiredRoles: ['beats_admin'], }, async (context, request, response) => { - const beatsManagement = context.beatsManagement!; + const beatsManagement = context.beatsManagement; const accessToken = request.headers['kbn-beats-access-token'] as string; const { beatId } = request.params; const user = beatsManagement.framework.getUser(request); diff --git a/x-pack/plugins/beats_management/server/routes/configurations/delete.ts b/x-pack/plugins/beats_management/server/routes/configurations/delete.ts index b60d3bd2d5a94..4fee192c93626 100644 --- a/x-pack/plugins/beats_management/server/routes/configurations/delete.ts +++ b/x-pack/plugins/beats_management/server/routes/configurations/delete.ts @@ -5,12 +5,12 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { ReturnTypeBulkDelete } from '../../../common/return_types'; -export const registerDeleteConfigurationBlocksRoute = (router: IRouter) => { +export const registerDeleteConfigurationBlocksRoute = (router: BeatsManagementRouter) => { router.delete( { path: '/api/beats/configurations/{ids}', @@ -26,7 +26,7 @@ export const registerDeleteConfigurationBlocksRoute = (router: IRouter) => { requiredRoles: ['beats_admin'], }, async (context, request, response) => { - const beatsManagement = context.beatsManagement!; + const beatsManagement = context.beatsManagement; const ids = request.params.ids.split(',').filter((id) => id.length > 0); const user = beatsManagement.framework.getUser(request); diff --git a/x-pack/plugins/beats_management/server/routes/configurations/get.ts b/x-pack/plugins/beats_management/server/routes/configurations/get.ts index 6f422ca9ca8bd..def913e0204b5 100644 --- a/x-pack/plugins/beats_management/server/routes/configurations/get.ts +++ b/x-pack/plugins/beats_management/server/routes/configurations/get.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { ConfigurationBlock } from '../../../common/domain_types'; import { ReturnTypeList } from '../../../common/return_types'; -export const registerGetConfigurationBlocksRoute = (router: IRouter) => { +export const registerGetConfigurationBlocksRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/configurations/{tagIds}/{page?}', @@ -28,7 +28,7 @@ export const registerGetConfigurationBlocksRoute = (router: IRouter) => { requiredRoles: ['beats_admin'], }, async (context, request, response) => { - const beatsManagement = context.beatsManagement!; + const beatsManagement = context.beatsManagement; const tagIds = request.params.tagIds.split(',').filter((id) => id.length > 0); const user = beatsManagement.framework.getUser(request); const result = await beatsManagement.configurationBlocks.getForTags( diff --git a/x-pack/plugins/beats_management/server/routes/configurations/upsert.ts b/x-pack/plugins/beats_management/server/routes/configurations/upsert.ts index e235b172e7d0b..002e981875324 100644 --- a/x-pack/plugins/beats_management/server/routes/configurations/upsert.ts +++ b/x-pack/plugins/beats_management/server/routes/configurations/upsert.ts @@ -7,7 +7,7 @@ import { PathReporter } from 'io-ts/lib/PathReporter'; import { isLeft } from 'fp-ts/lib/Either'; import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants'; import { ConfigurationBlock, @@ -16,7 +16,7 @@ import { import { ReturnTypeBulkUpsert } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerUpsertConfigurationBlocksRoute = (router: IRouter) => { +export const registerUpsertConfigurationBlocksRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file router.put( { @@ -31,7 +31,7 @@ export const registerUpsertConfigurationBlocksRoute = (router: IRouter) => { requiredRoles: ['beats_admin'], }, async (context, request, response) => { - const beatsManagement = context.beatsManagement!; + const beatsManagement = context.beatsManagement; const user = beatsManagement.framework.getUser(request); const input = request.body as ConfigurationBlock[]; diff --git a/x-pack/plugins/beats_management/server/routes/index.ts b/x-pack/plugins/beats_management/server/routes/index.ts index 423ecc85a5798..14af4e274b5ae 100644 --- a/x-pack/plugins/beats_management/server/routes/index.ts +++ b/x-pack/plugins/beats_management/server/routes/index.ts @@ -3,8 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../lib/types'; import { registerDeleteConfigurationBlocksRoute, registerGetConfigurationBlocksRoute, @@ -29,7 +28,7 @@ import { registerGetBeatConfigurationRoute, } from './beats'; -export const registerRoutes = (router: IRouter) => { +export const registerRoutes = (router: BeatsManagementRouter) => { // configurations registerGetConfigurationBlocksRoute(router); registerDeleteConfigurationBlocksRoute(router); diff --git a/x-pack/plugins/beats_management/server/routes/tags/assignable.ts b/x-pack/plugins/beats_management/server/routes/tags/assignable.ts index 60d4748bf1fa6..254d1015221b5 100644 --- a/x-pack/plugins/beats_management/server/routes/tags/assignable.ts +++ b/x-pack/plugins/beats_management/server/routes/tags/assignable.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; import { flatten } from 'lodash'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { BeatTag } from '../../../common/domain_types'; import { ReturnTypeBulkGet } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerAssignableTagsRoute = (router: IRouter) => { +export const registerAssignableTagsRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/tags/assignable/{beatIds}', diff --git a/x-pack/plugins/beats_management/server/routes/tags/delete.ts b/x-pack/plugins/beats_management/server/routes/tags/delete.ts index 78d0c80d42060..4d689dfe49c58 100644 --- a/x-pack/plugins/beats_management/server/routes/tags/delete.ts +++ b/x-pack/plugins/beats_management/server/routes/tags/delete.ts @@ -5,12 +5,12 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { ReturnTypeBulkDelete } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerDeleteTagsWithIdsRoute = (router: IRouter) => { +export const registerDeleteTagsWithIdsRoute = (router: BeatsManagementRouter) => { router.delete( { path: '/api/beats/tags/{tagIds}', diff --git a/x-pack/plugins/beats_management/server/routes/tags/get.ts b/x-pack/plugins/beats_management/server/routes/tags/get.ts index 48da829aa09e5..a4154eaf092a4 100644 --- a/x-pack/plugins/beats_management/server/routes/tags/get.ts +++ b/x-pack/plugins/beats_management/server/routes/tags/get.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { BeatTag } from '../../../common/domain_types'; import { ReturnTypeBulkGet } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerGetTagsWithIdsRoute = (router: IRouter) => { +export const registerGetTagsWithIdsRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/tags/{tagIds}', diff --git a/x-pack/plugins/beats_management/server/routes/tags/list.ts b/x-pack/plugins/beats_management/server/routes/tags/list.ts index ce913cda337c5..3faa3d0f6662c 100644 --- a/x-pack/plugins/beats_management/server/routes/tags/list.ts +++ b/x-pack/plugins/beats_management/server/routes/tags/list.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'kibana/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { BeatTag } from '../../../common/domain_types'; import { ReturnTypeList } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerListTagsRoute = (router: IRouter) => { +export const registerListTagsRoute = (router: BeatsManagementRouter) => { router.get( { path: '/api/beats/tags', diff --git a/x-pack/plugins/beats_management/server/routes/tags/set.ts b/x-pack/plugins/beats_management/server/routes/tags/set.ts index ef9e181514a55..b80faa5c5c5ef 100644 --- a/x-pack/plugins/beats_management/server/routes/tags/set.ts +++ b/x-pack/plugins/beats_management/server/routes/tags/set.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants'; import { BeatTag } from '../../../common/domain_types'; import { ReturnTypeUpsert } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; -export const registerSetTagRoute = (router: IRouter) => { +export const registerSetTagRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file router.put( { diff --git a/x-pack/plugins/beats_management/server/routes/tokens/create.ts b/x-pack/plugins/beats_management/server/routes/tokens/create.ts index 2fd7d4614c570..5a2f04e21fcc1 100644 --- a/x-pack/plugins/beats_management/server/routes/tokens/create.ts +++ b/x-pack/plugins/beats_management/server/routes/tokens/create.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { BeatsManagementRouter } from '../../lib/types'; import { REQUIRED_LICENSES } from '../../../common/constants/security'; import { ReturnTypeBulkCreate } from '../../../common/return_types'; import { wrapRouteWithSecurity } from '../wrap_route_with_security'; const DEFAULT_NUM_TOKENS = 1; -export const registerCreateTokenRoute = (router: IRouter) => { +export const registerCreateTokenRoute = (router: BeatsManagementRouter) => { // TODO: write to Kibana audit log file router.post( { diff --git a/x-pack/plugins/beats_management/server/routes/wrap_route_with_security.ts b/x-pack/plugins/beats_management/server/routes/wrap_route_with_security.ts index ad4f8080127b2..ab116d2af3b2c 100644 --- a/x-pack/plugins/beats_management/server/routes/wrap_route_with_security.ts +++ b/x-pack/plugins/beats_management/server/routes/wrap_route_with_security.ts @@ -4,24 +4,24 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, - RouteMethod, -} from 'src/core/server'; +import { KibanaRequest, KibanaResponseFactory, RequestHandler, RouteMethod } from 'src/core/server'; import { difference } from 'lodash'; +import type { BeatsManagementRequestHandlerContext } from '../lib/types'; -export function wrapRouteWithSecurity( +export function wrapRouteWithSecurity< + P, + Q, + B, + Context extends BeatsManagementRequestHandlerContext +>( { requiredLicense = [], requiredRoles = [], }: { requiredLicense?: string[]; requiredRoles?: string[] }, - handler: RequestHandler -): RequestHandler { + handler: RequestHandler +): RequestHandler { return async ( - context: RequestHandlerContext, + context: Context, request: KibanaRequest, response: KibanaResponseFactory ) => { diff --git a/x-pack/plugins/case/server/client/index.test.ts b/x-pack/plugins/case/server/client/index.test.ts index 0c54db11287d8..a7f093f42357c 100644 --- a/x-pack/plugins/case/server/client/index.test.ts +++ b/x-pack/plugins/case/server/client/index.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest } from 'kibana/server'; import { savedObjectsClientMock } from '../../../../../src/core/server/mocks'; import { createCaseClient } from '.'; import { @@ -19,6 +19,7 @@ import { create } from './cases/create'; import { update } from './cases/update'; import { addComment } from './comments/add'; import { updateAlertsStatus } from './alerts/update_status'; +import type { CasesRequestHandlerContext } from '../types'; jest.mock('./cases/create'); jest.mock('./cases/update'); @@ -32,7 +33,7 @@ const connectorMappingsService = connectorMappingsServiceMock(); const request = {} as KibanaRequest; const savedObjectsClient = savedObjectsClientMock.create(); const userActionService = createUserActionServiceMock(); -const context = {} as RequestHandlerContext; +const context = {} as CasesRequestHandlerContext; const createMock = create as jest.Mock; const updateMock = update as jest.Mock; @@ -57,7 +58,6 @@ describe('createCaseClient()', () => { caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, @@ -68,7 +68,6 @@ describe('createCaseClient()', () => { caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, @@ -79,7 +78,6 @@ describe('createCaseClient()', () => { caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, diff --git a/x-pack/plugins/case/server/client/index.ts b/x-pack/plugins/case/server/client/index.ts index 70eb3282dd243..c4eb1334eb1e4 100644 --- a/x-pack/plugins/case/server/client/index.ts +++ b/x-pack/plugins/case/server/client/index.ts @@ -30,7 +30,6 @@ export const createCaseClient = ({ caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, @@ -40,7 +39,6 @@ export const createCaseClient = ({ caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, @@ -50,7 +48,6 @@ export const createCaseClient = ({ caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, @@ -61,7 +58,6 @@ export const createCaseClient = ({ caseConfigureService, caseService, connectorMappingsService, - context, request, savedObjectsClient, userActionService, diff --git a/x-pack/plugins/case/server/client/mocks.ts b/x-pack/plugins/case/server/client/mocks.ts index 78cb7f71cef4c..2db00ff8ca6d6 100644 --- a/x-pack/plugins/case/server/client/mocks.ts +++ b/x-pack/plugins/case/server/client/mocks.ts @@ -5,7 +5,7 @@ */ import { omit } from 'lodash/fp'; -import { KibanaRequest, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest } from 'kibana/server'; import { loggingSystemMock } from '../../../../../src/core/server/mocks'; import { actionsClientMock } from '../../../actions/server/mocks'; import { @@ -19,6 +19,7 @@ import { CaseClient } from './types'; import { authenticationMock } from '../routes/api/__fixtures__'; import { createCaseClient } from '.'; import { getActions } from '../routes/api/__mocks__/request_responses'; +import type { CasesRequestHandlerContext } from '../types'; export type CaseClientMock = jest.Mocked; export const createCaseClientMock = (): CaseClientMock => ({ @@ -92,7 +93,7 @@ export const createCaseClientWithMockSavedObjectsClient = async ({ connectorMappingsService, userActionService, alertsService, - context: (omit(omitFromContext, context) as unknown) as RequestHandlerContext, + context: (omit(omitFromContext, context) as unknown) as CasesRequestHandlerContext, }); return { client: caseClient, diff --git a/x-pack/plugins/case/server/client/types.ts b/x-pack/plugins/case/server/client/types.ts index ec83f1ec1ff7d..fe80b1ba46a7e 100644 --- a/x-pack/plugins/case/server/client/types.ts +++ b/x-pack/plugins/case/server/client/types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, SavedObjectsClientContract, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest, SavedObjectsClientContract } from 'kibana/server'; import { ActionsClient } from '../../../actions/server'; import { CasePostRequest, @@ -23,6 +23,8 @@ import { AlertServiceContract, } from '../services'; import { ConnectorMappingsServiceSetup } from '../services/connector_mappings'; +import type { CasesRequestHandlerContext } from '../types'; + export interface CaseClientCreate { theCase: CasePostRequest; } @@ -43,8 +45,6 @@ export interface CaseClientUpdateAlertsStatus { status: CaseStatuses; } -type PartialExceptFor = Partial & Pick; - export interface CaseClientFactoryArguments { caseConfigureService: CaseConfigureServiceSetup; caseService: CaseServiceSetup; @@ -53,7 +53,7 @@ export interface CaseClientFactoryArguments { savedObjectsClient: SavedObjectsClientContract; userActionService: CaseUserActionServiceSetup; alertsService: AlertServiceContract; - context?: PartialExceptFor; + context?: Omit; } export interface ConfigureFields { diff --git a/x-pack/plugins/case/server/connectors/case/index.ts b/x-pack/plugins/case/server/connectors/case/index.ts index 2195786f718ab..ca4c30d1ac43b 100644 --- a/x-pack/plugins/case/server/connectors/case/index.ts +++ b/x-pack/plugins/case/server/connectors/case/index.ts @@ -6,7 +6,7 @@ import { curry } from 'lodash'; -import { KibanaRequest, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest } from 'kibana/server'; import { ActionTypeExecutorResult } from '../../../../actions/common'; import { CasePatchRequest, CasePostRequest } from '../../../common/api'; import { createCaseClient } from '../../client'; @@ -18,6 +18,7 @@ import { CaseActionTypeExecutorOptions, } from './types'; import * as i18n from './translations'; +import type { CasesRequestHandlerContext } from '../../types'; import { GetActionTypeParams } from '..'; @@ -78,7 +79,7 @@ async function executor( userActionService, alertsService, // TODO: When case connector is enabled we should figure out how to pass the context. - context: {} as RequestHandlerContext, + context: {} as CasesRequestHandlerContext, }); if (!supportedSubActions.includes(subAction)) { diff --git a/x-pack/plugins/case/server/plugin.ts b/x-pack/plugins/case/server/plugin.ts index 915656895e8c8..0b9712e78c2bc 100644 --- a/x-pack/plugins/case/server/plugin.ts +++ b/x-pack/plugins/case/server/plugin.ts @@ -5,14 +5,7 @@ */ import { first, map } from 'rxjs/operators'; -import { - IContextProvider, - KibanaRequest, - Logger, - PluginInitializerContext, - RequestHandler, - RequestHandlerContext, -} from 'kibana/server'; +import { IContextProvider, KibanaRequest, Logger, PluginInitializerContext } from 'kibana/server'; import { CoreSetup, CoreStart } from 'src/core/server'; import { SecurityPluginSetup } from '../../security/server'; @@ -42,6 +35,7 @@ import { } from './services'; import { createCaseClient } from './client'; import { registerConnectors } from './connectors'; +import type { CasesRequestHandlerContext } from './types'; function createConfig$(context: PluginInitializerContext) { return context.config.create().pipe(map((config) => config)); @@ -91,7 +85,7 @@ export class CasePlugin { this.userActionService = await new CaseUserActionService(this.log).setup(); this.alertsService = new AlertService(); - core.http.registerRouteHandlerContext( + core.http.registerRouteHandlerContext( APP_ID, this.createRouteHandlerContext({ core, @@ -103,7 +97,7 @@ export class CasePlugin { }) ); - const router = core.http.createRouter(); + const router = core.http.createRouter(); initCaseApi({ caseService: this.caseService, caseConfigureService: this.caseConfigureService, @@ -128,7 +122,7 @@ export class CasePlugin { this.alertsService!.initialize(core.elasticsearch.client); const getCaseClientWithRequestAndContext = async ( - context: RequestHandlerContext, + context: CasesRequestHandlerContext, request: KibanaRequest ) => { return createCaseClient({ @@ -166,7 +160,7 @@ export class CasePlugin { connectorMappingsService: ConnectorMappingsServiceSetup; userActionService: CaseUserActionServiceSetup; alertsService: AlertServiceContract; - }): IContextProvider, typeof APP_ID> => { + }): IContextProvider => { return async (context, request) => { const [{ savedObjects }] = await core.getStartServices(); return { diff --git a/x-pack/plugins/case/server/routes/api/__fixtures__/route_contexts.ts b/x-pack/plugins/case/server/routes/api/__fixtures__/route_contexts.ts index b2d232dbb7cca..40911496d6494 100644 --- a/x-pack/plugins/case/server/routes/api/__fixtures__/route_contexts.ts +++ b/x-pack/plugins/case/server/routes/api/__fixtures__/route_contexts.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext, KibanaRequest } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; import { loggingSystemMock, elasticsearchServiceMock } from 'src/core/server/mocks'; import { actionsClientMock } from '../../../../../actions/server/mocks'; import { createCaseClient } from '../../../client'; @@ -16,6 +16,7 @@ import { } from '../../../services'; import { getActions } from '../__mocks__/request_responses'; import { authenticationMock } from '../__fixtures__'; +import type { CasesRequestHandlerContext } from '../../../types'; export const createRouteContext = async (client: any, badAuth = false) => { const actionsMock = actionsClientMock.create(); @@ -49,7 +50,7 @@ export const createRouteContext = async (client: any, badAuth = false) => { getSignalsIndex: () => '.siem-signals', }), }, - } as unknown) as RequestHandlerContext; + } as unknown) as CasesRequestHandlerContext; const connectorMappingsService = await connectorMappingsServicePlugin.setup(); const caseClient = createCaseClient({ diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts index c77d2bd45a795..b744a6dc04810 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts @@ -59,6 +59,7 @@ describe('GET connectors', () => { }) ); + // @ts-expect-error context.actions = undefined; const res = await routeHandler(context, req, kibanaResponseFactory); diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/post_push_to_service.test.ts b/x-pack/plugins/case/server/routes/api/cases/configure/post_push_to_service.test.ts index ff0939fdcce1f..4746a203b40f4 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/post_push_to_service.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/post_push_to_service.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { kibanaResponseFactory, RequestHandler, RequestHandlerContext } from 'src/core/server'; +import { kibanaResponseFactory, RequestHandler } from 'src/core/server'; import { httpServerMock } from 'src/core/server/mocks'; import { @@ -17,6 +17,7 @@ import { import { initPostPushToService } from './post_push_to_service'; import { executePushResponse, newPostPushRequest } from '../../__mocks__/request_responses'; import { CASE_CONFIGURE_PUSH_URL } from '../../../../../common/constants'; +import type { CasesRequestHandlerContext } from '../../../../types'; describe('Post push to service', () => { let routeHandler: RequestHandler; @@ -28,7 +29,7 @@ describe('Post push to service', () => { }, body: newPostPushRequest, }); - let context: RequestHandlerContext; + let context: CasesRequestHandlerContext; beforeAll(async () => { routeHandler = await createRoute(initPostPushToService, 'post'); const spyOnDate = jest.spyOn(global, 'Date') as jest.SpyInstance<{}, []>; @@ -67,7 +68,7 @@ describe('Post push to service', () => { }; }, }, - } as unknown) as RequestHandlerContext; + } as unknown) as CasesRequestHandlerContext; const res = await routeHandler(betterContext, req, kibanaResponseFactory); @@ -81,7 +82,7 @@ describe('Post push to service', () => { const betterContext = ({ ...context, case: null, - } as unknown) as RequestHandlerContext; + } as unknown) as CasesRequestHandlerContext; const res = await routeHandler(betterContext, req, kibanaResponseFactory); expect(res.status).toEqual(400); @@ -94,7 +95,7 @@ describe('Post push to service', () => { const betterContext = ({ ...context, actions: null, - } as unknown) as RequestHandlerContext; + } as unknown) as CasesRequestHandlerContext; const res = await routeHandler(betterContext, req, kibanaResponseFactory); expect(res.status).toEqual(404); diff --git a/x-pack/plugins/case/server/routes/api/types.ts b/x-pack/plugins/case/server/routes/api/types.ts index 0b93d844fe9ab..c01ec3d232a0a 100644 --- a/x-pack/plugins/case/server/routes/api/types.ts +++ b/x-pack/plugins/case/server/routes/api/types.ts @@ -4,19 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; -import { +import type { CaseConfigureServiceSetup, CaseServiceSetup, CaseUserActionServiceSetup, ConnectorMappingsServiceSetup, } from '../../services'; +import type { CasesRouter } from '../../types'; + export interface RouteDeps { caseConfigureService: CaseConfigureServiceSetup; caseService: CaseServiceSetup; connectorMappingsService: ConnectorMappingsServiceSetup; - router: IRouter; + router: CasesRouter; userActionService: CaseUserActionServiceSetup; } diff --git a/x-pack/plugins/case/server/types.ts b/x-pack/plugins/case/server/types.ts index d0dfc26aa7b8c..34be3a89716a5 100644 --- a/x-pack/plugins/case/server/types.ts +++ b/x-pack/plugins/case/server/types.ts @@ -4,19 +4,27 @@ * you may not use this file except in compliance with the Elastic License. */ -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { AppRequestContext } from '../../security_solution/server/types'; +import type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { AppRequestContext } from '../../security_solution/server'; +import type { ActionsApiRequestHandlerContext } from '../../actions/server'; import { CaseClient } from './client'; export interface CaseRequestContext { getCaseClient: () => CaseClient; } -declare module 'src/core/server' { - interface RequestHandlerContext { - case?: CaseRequestContext; - // TODO: Remove when triggers_ui do not import case's types. - // PR https://github.com/elastic/kibana/pull/84587. - securitySolution?: AppRequestContext; - } +/** + * @internal + */ +export interface CasesRequestHandlerContext extends RequestHandlerContext { + case: CaseRequestContext; + actions: ActionsApiRequestHandlerContext; + // TODO: Remove when triggers_ui do not import case's types. + // PR https://github.com/elastic/kibana/pull/84587. + securitySolution: AppRequestContext; } + +/** + * @internal + */ +export type CasesRouter = IRouter; diff --git a/x-pack/plugins/cross_cluster_replication/server/plugin.ts b/x-pack/plugins/cross_cluster_replication/server/plugin.ts index d40a53f289873..3fb488dde4c3d 100644 --- a/x-pack/plugins/cross_cluster_replication/server/plugin.ts +++ b/x-pack/plugins/cross_cluster_replication/server/plugin.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -declare module 'src/core/server' { - interface RequestHandlerContext { - crossClusterReplication?: CrossClusterReplicationContext; - } -} - import { Observable } from 'rxjs'; import { first } from 'rxjs/operators'; import { i18n } from '@kbn/i18n'; @@ -20,12 +14,11 @@ import { Logger, PluginInitializerContext, LegacyAPICaller, - ILegacyScopedClusterClient, } from 'src/core/server'; import { Index } from '../../index_management/server'; import { PLUGIN } from '../common/constants'; -import { Dependencies } from './types'; +import type { Dependencies, CcrRequestHandlerContext } from './types'; import { registerApiRoutes } from './routes'; import { License } from './services'; import { elasticsearchJsPlugin } from './client/elasticsearch_ccr'; @@ -33,10 +26,6 @@ import { CrossClusterReplicationConfig } from './config'; import { isEsError } from './shared_imports'; import { formatEsError } from './lib/format_es_error'; -interface CrossClusterReplicationContext { - client: ILegacyScopedClusterClient; -} - async function getCustomEsClient(getStartServices: CoreSetup['getStartServices']) { const [core] = await getStartServices(); // Extend the elasticsearchJs client with additional endpoints. @@ -137,12 +126,15 @@ export class CrossClusterReplicationServerPlugin implements Plugin { - this.ccrEsClient = this.ccrEsClient ?? (await getCustomEsClient(getStartServices)); - return { - client: this.ccrEsClient.asScoped(request), - }; - }); + http.registerRouteHandlerContext( + 'crossClusterReplication', + async (ctx, request) => { + this.ccrEsClient = this.ccrEsClient ?? (await getCustomEsClient(getStartServices)); + return { + client: this.ccrEsClient.asScoped(request), + }; + } + ); registerApiRoutes({ router: http.createRouter(), diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts index 521de77180974..463df5cc20794 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts @@ -49,7 +49,7 @@ export const registerUpdateRoute = ({ try { const { follower_indices: followerIndices, - } = await context.crossClusterReplication!.client.callAsCurrentUser('ccr.info', { id }); + } = await context.crossClusterReplication.client.callAsCurrentUser('ccr.info', { id }); const followerIndexInfo = followerIndices && followerIndices[0]; diff --git a/x-pack/plugins/cross_cluster_replication/server/services/license.ts b/x-pack/plugins/cross_cluster_replication/server/services/license.ts index 5424092a01ee5..cccc54dcc058a 100644 --- a/x-pack/plugins/cross_cluster_replication/server/services/license.ts +++ b/x-pack/plugins/cross_cluster_replication/server/services/license.ts @@ -4,12 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ import { Logger } from 'src/core/server'; -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from 'src/core/server'; +import { KibanaRequest, KibanaResponseFactory, RequestHandler } from 'src/core/server'; +import type { CcrRequestHandlerContext } from '../types'; import { LicensingPluginSetup } from '../../../licensing/server'; import { LicenseType } from '../../../licensing/common/types'; @@ -59,11 +55,11 @@ export class License { }); } - guardApiRoute(handler: RequestHandler) { + guardApiRoute(handler: RequestHandler) { const license = this; return function licenseCheck( - ctx: RequestHandlerContext, + ctx: CcrRequestHandlerContext, request: KibanaRequest, response: KibanaResponseFactory ) { diff --git a/x-pack/plugins/cross_cluster_replication/server/types.ts b/x-pack/plugins/cross_cluster_replication/server/types.ts index 62c96b48c4373..48ded67566b30 100644 --- a/x-pack/plugins/cross_cluster_replication/server/types.ts +++ b/x-pack/plugins/cross_cluster_replication/server/types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import { IRouter, ILegacyScopedClusterClient, RequestHandlerContext } from 'src/core/server'; import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; import { LicensingPluginSetup } from '../../licensing/server'; import { IndexManagementPluginSetup } from '../../index_management/server'; @@ -21,10 +21,24 @@ export interface Dependencies { } export interface RouteDependencies { - router: IRouter; + router: CcrPluginRouter; license: License; lib: { isEsError: typeof isEsError; formatEsError: typeof formatEsError; }; } + +/** + * @internal + */ +export interface CcrRequestHandlerContext extends RequestHandlerContext { + crossClusterReplication: { + client: ILegacyScopedClusterClient; + }; +} + +/** + * @internal + */ +type CcrPluginRouter = IRouter; diff --git a/x-pack/plugins/data_enhanced/server/plugin.ts b/x-pack/plugins/data_enhanced/server/plugin.ts index 35a838f253ac6..cff0ee3efd738 100644 --- a/x-pack/plugins/data_enhanced/server/plugin.ts +++ b/x-pack/plugins/data_enhanced/server/plugin.ts @@ -21,6 +21,7 @@ import { eqlSearchStrategyProvider, } from './search'; import { getUiSettings } from './ui_settings'; +import type { DataEnhancedRequestHandlerContext } from './type'; interface SetupDependencies { data: DataPluginSetup; @@ -73,7 +74,7 @@ export class EnhancedDataServerPlugin }, }); - const router = core.http.createRouter(); + const router = core.http.createRouter(); registerSessionRoutes(router, this.logger); this.sessionService.setup(core, { diff --git a/x-pack/plugins/data_enhanced/server/routes/mocks.ts b/x-pack/plugins/data_enhanced/server/routes/mocks.ts index 3e7b89ed2cca6..4bad563bf393b 100644 --- a/x-pack/plugins/data_enhanced/server/routes/mocks.ts +++ b/x-pack/plugins/data_enhanced/server/routes/mocks.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'kibana/server'; +import type { DataRequestHandlerContext } from '../../../../../src/plugins/data/server'; import { coreMock } from '../../../../../src/core/server/mocks'; export function createSearchRequestHandlerContext() { @@ -22,5 +22,5 @@ export function createSearchRequestHandlerContext() { update: jest.fn(), }, }, - } as unknown) as jest.Mocked; + } as unknown) as jest.Mocked; } diff --git a/x-pack/plugins/data_enhanced/server/routes/session.test.ts b/x-pack/plugins/data_enhanced/server/routes/session.test.ts index 0251660202597..c4433b562e97a 100644 --- a/x-pack/plugins/data_enhanced/server/routes/session.test.ts +++ b/x-pack/plugins/data_enhanced/server/routes/session.test.ts @@ -5,15 +5,19 @@ */ import type { MockedKeys } from '@kbn/utility-types/jest'; -import type { CoreSetup, Logger, RequestHandlerContext } from 'kibana/server'; + +import type { CoreSetup, Logger } from 'kibana/server'; import { coreMock, httpServerMock } from '../../../../../src/core/server/mocks'; -import { PluginStart as DataPluginStart } from '../../../../../src/plugins/data/server'; +import type { + PluginStart as DataPluginStart, + DataRequestHandlerContext, +} from '../../../../../src/plugins/data/server'; import { createSearchRequestHandlerContext } from './mocks'; import { registerSessionRoutes } from './session'; describe('registerSessionRoutes', () => { let mockCoreSetup: MockedKeys>; - let mockContext: jest.Mocked; + let mockContext: jest.Mocked; let mockLogger: Logger; beforeEach(() => { diff --git a/x-pack/plugins/data_enhanced/server/routes/session.ts b/x-pack/plugins/data_enhanced/server/routes/session.ts index 9e61dd39c83b8..cbf683bd18fd2 100644 --- a/x-pack/plugins/data_enhanced/server/routes/session.ts +++ b/x-pack/plugins/data_enhanced/server/routes/session.ts @@ -5,10 +5,11 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter, Logger } from 'src/core/server'; +import { Logger } from 'src/core/server'; import { reportServerError } from '../../../../../src/plugins/kibana_utils/server'; +import { DataEnhancedPluginRouter } from '../type'; -export function registerSessionRoutes(router: IRouter, logger: Logger): void { +export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger: Logger): void { router.post( { path: '/internal/session', diff --git a/x-pack/plugins/data_enhanced/server/type.ts b/x-pack/plugins/data_enhanced/server/type.ts new file mode 100644 index 0000000000000..a0dcbd81a5dde --- /dev/null +++ b/x-pack/plugins/data_enhanced/server/type.ts @@ -0,0 +1,18 @@ +/* + * 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 type { IRouter } from 'kibana/server'; +import type { DataRequestHandlerContext } from '../../../../src/plugins/data/server'; + +/** + * @internal + */ +export type DataEnhancedRequestHandlerContext = DataRequestHandlerContext; + +/** + * @internal + */ +export type DataEnhancedPluginRouter = IRouter; diff --git a/x-pack/plugins/event_log/server/plugin.ts b/x-pack/plugins/event_log/server/plugin.ts index 03125f3005c3d..3bf726de71856 100644 --- a/x-pack/plugins/event_log/server/plugin.ts +++ b/x-pack/plugins/event_log/server/plugin.ts @@ -15,11 +15,11 @@ import { LegacyClusterClient, SharedGlobalConfig, IContextProvider, - RequestHandler, } from 'src/core/server'; import { SpacesPluginStart } from '../../spaces/server'; -import { +import type { + EventLogRequestHandlerContext, IEventLogConfig, IEventLogService, IEventLogger, @@ -97,10 +97,13 @@ export class Plugin implements CorePlugin( + 'eventLog', + this.createRouteHandlerContext() + ); // Routes - const router = core.http.createRouter(); + const router = core.http.createRouter(); // Register routes findRoute(router, this.systemLogger); findByIdsRoute(router, this.systemLogger); @@ -169,7 +172,7 @@ export class Plugin implements CorePlugin, + EventLogRequestHandlerContext, 'eventLog' > => { return async (context, request) => { diff --git a/x-pack/plugins/event_log/server/routes/find.ts b/x-pack/plugins/event_log/server/routes/find.ts index 50785de72cfc5..aa882fb002752 100644 --- a/x-pack/plugins/event_log/server/routes/find.ts +++ b/x-pack/plugins/event_log/server/routes/find.ts @@ -5,15 +5,13 @@ */ import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, +import type { KibanaRequest, IKibanaResponse, KibanaResponseFactory, Logger, } from 'src/core/server'; - +import type { EventLogRouter, EventLogRequestHandlerContext } from '../types'; import { BASE_EVENT_LOG_API_PATH } from '../../common'; import { findOptionsSchema, FindOptionsType } from '../event_log_client'; @@ -22,7 +20,7 @@ const paramSchema = schema.object({ id: schema.string(), }); -export const findRoute = (router: IRouter, systemLogger: Logger) => { +export const findRoute = (router: EventLogRouter, systemLogger: Logger) => { router.get( { path: `${BASE_EVENT_LOG_API_PATH}/{type}/{id}/_find`, @@ -32,7 +30,7 @@ export const findRoute = (router: IRouter, systemLogger: Logger) => { }, }, router.handleLegacyErrors(async function ( - context: RequestHandlerContext, + context: EventLogRequestHandlerContext, req: KibanaRequest, FindOptionsType, unknown>, res: KibanaResponseFactory ): Promise { diff --git a/x-pack/plugins/event_log/server/routes/find_by_ids.ts b/x-pack/plugins/event_log/server/routes/find_by_ids.ts index a7ee0f35ac59e..a846c93eb95ed 100644 --- a/x-pack/plugins/event_log/server/routes/find_by_ids.ts +++ b/x-pack/plugins/event_log/server/routes/find_by_ids.ts @@ -5,14 +5,13 @@ */ import { schema, TypeOf } from '@kbn/config-schema'; -import { - IRouter, - RequestHandlerContext, +import type { KibanaRequest, IKibanaResponse, KibanaResponseFactory, Logger, } from 'src/core/server'; +import type { EventLogRouter, EventLogRequestHandlerContext } from '../types'; import { BASE_EVENT_LOG_API_PATH } from '../../common'; import { findOptionsSchema, FindOptionsType } from '../event_log_client'; @@ -25,7 +24,7 @@ const bodySchema = schema.object({ ids: schema.arrayOf(schema.string(), { defaultValue: [] }), }); -export const findByIdsRoute = (router: IRouter, systemLogger: Logger) => { +export const findByIdsRoute = (router: EventLogRouter, systemLogger: Logger) => { router.post( { path: `${BASE_EVENT_LOG_API_PATH}/{type}/_find`, @@ -36,7 +35,7 @@ export const findByIdsRoute = (router: IRouter, systemLogger: Logger) => { }, }, router.handleLegacyErrors(async function ( - context: RequestHandlerContext, + context: EventLogRequestHandlerContext, req: KibanaRequest, FindOptionsType, TypeOf>, res: KibanaResponseFactory ): Promise { diff --git a/x-pack/plugins/event_log/server/types.ts b/x-pack/plugins/event_log/server/types.ts index ff2ae81632923..e995e979a0808 100644 --- a/x-pack/plugins/event_log/server/types.ts +++ b/x-pack/plugins/event_log/server/types.ts @@ -6,7 +6,7 @@ import { Observable } from 'rxjs'; import { schema, TypeOf } from '@kbn/config-schema'; -import { KibanaRequest } from 'src/core/server'; +import type { IRouter, KibanaRequest, RequestHandlerContext } from 'src/core/server'; export { IEvent, IValidatedEvent, EventSchema, ECS_VERSION } from '../generated/schemas'; import { IEvent } from '../generated/schemas'; @@ -26,14 +26,6 @@ export const ConfigSchema = schema.object({ export type IEventLogConfig = TypeOf; export type IEventLogConfig$ = Observable>; -declare module 'src/core/server' { - interface RequestHandlerContext { - eventLog?: { - getEventLogClient: () => IEventLogClient; - }; - } -} - // the object exposed by plugin.setup() export interface IEventLogService { isEnabled(): boolean; @@ -63,3 +55,22 @@ export interface IEventLogger { startTiming(event: IEvent): void; stopTiming(event: IEvent): void; } + +/** + * @internal + */ +export interface EventLogApiRequestHandlerContext { + getEventLogClient(): IEventLogClient; +} + +/** + * @internal + */ +export interface EventLogRequestHandlerContext extends RequestHandlerContext { + eventLog: EventLogApiRequestHandlerContext; +} + +/** + * @internal + */ +export type EventLogRouter = IRouter; diff --git a/x-pack/plugins/features/server/routes/index.ts b/x-pack/plugins/features/server/routes/index.ts index b2bfa8b0296b7..cd6d220961831 100644 --- a/x-pack/plugins/features/server/routes/index.ts +++ b/x-pack/plugins/features/server/routes/index.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from '../../../../../src/core/server'; +import type { FeaturesPluginRouter } from '../types'; import { FeatureRegistry } from '../feature_registry'; /** * Describes parameters used to define HTTP routes. */ export interface RouteDefinitionParams { - router: IRouter; + router: FeaturesPluginRouter; featureRegistry: FeatureRegistry; } diff --git a/x-pack/plugins/features/server/types.ts b/x-pack/plugins/features/server/types.ts new file mode 100644 index 0000000000000..d42fa1c498d48 --- /dev/null +++ b/x-pack/plugins/features/server/types.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 type { RequestHandlerContext, IRouter } from 'src/core/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; + +/** + * @internal + */ +export interface FeaturesRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; +} + +/** + * @internal + */ +export type FeaturesPluginRouter = IRouter; diff --git a/x-pack/plugins/global_search/server/mocks.ts b/x-pack/plugins/global_search/server/mocks.ts index 88be7f6e861a1..f0498302808e4 100644 --- a/x-pack/plugins/global_search/server/mocks.ts +++ b/x-pack/plugins/global_search/server/mocks.ts @@ -9,9 +9,11 @@ import { GlobalSearchPluginSetup, GlobalSearchPluginStart, RouteHandlerGlobalSearchContext, + GlobalSearchRequestHandlerContext, } from './types'; import { searchServiceMock } from './services/search_service.mock'; import { contextMock } from './services/context.mock'; +import { coreMock } from '../../../../src/core/server/mocks'; const createSetupMock = (): jest.Mocked => { const searchMock = searchServiceMock.createSetupContract(); @@ -41,9 +43,21 @@ const createRouteHandlerContextMock = (): jest.Mocked => { + const handlerContextMock = { + find: jest.fn(), + getSearchableTypes: jest.fn(), + }; + + handlerContextMock.find.mockReturnValue(of([])); + + return { core: coreMock.createRequestHandlerContext(), globalSearch: handlerContextMock }; +}; + export const globalSearchPluginMock = { createSetupContract: createSetupMock, createStartContract: createStartMock, createRouteHandlerContext: createRouteHandlerContextMock, createProviderContext: contextMock.create, + createRequestHandlerContext: createRequestHandlerContextMock, }; diff --git a/x-pack/plugins/global_search/server/plugin.ts b/x-pack/plugins/global_search/server/plugin.ts index 9d6844dde50f0..29c63efd64df0 100644 --- a/x-pack/plugins/global_search/server/plugin.ts +++ b/x-pack/plugins/global_search/server/plugin.ts @@ -14,16 +14,10 @@ import { registerRoutes } from './routes'; import { GlobalSearchPluginSetup, GlobalSearchPluginStart, - RouteHandlerGlobalSearchContext, + GlobalSearchRequestHandlerContext, } from './types'; import { GlobalSearchConfigType } from './config'; -declare module 'src/core/server' { - interface RequestHandlerContext { - globalSearch?: RouteHandlerGlobalSearchContext; - } -} - // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface GlobalSearchPluginSetupDeps {} export interface GlobalSearchPluginStartDeps { @@ -56,12 +50,15 @@ export class GlobalSearchPlugin registerRoutes(core.http.createRouter()); - core.http.registerRouteHandlerContext('globalSearch', (_, req) => { - return { - find: (term, options) => this.searchServiceStart!.find(term, options, req), - getSearchableTypes: () => this.searchServiceStart!.getSearchableTypes(req), - }; - }); + core.http.registerRouteHandlerContext( + 'globalSearch', + (_, req) => { + return { + find: (term, options) => this.searchServiceStart!.find(term, options, req), + getSearchableTypes: () => this.searchServiceStart!.getSearchableTypes(req), + }; + } + ); return { registerResultProvider, diff --git a/x-pack/plugins/global_search/server/routes/find.ts b/x-pack/plugins/global_search/server/routes/find.ts index 0b82a035348ed..f9bc0d8698821 100644 --- a/x-pack/plugins/global_search/server/routes/find.ts +++ b/x-pack/plugins/global_search/server/routes/find.ts @@ -6,10 +6,10 @@ import { reduce, map } from 'rxjs/operators'; import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import { GlobalSearchRouter } from '../types'; import { GlobalSearchFindError } from '../../common/errors'; -export const registerInternalFindRoute = (router: IRouter) => { +export const registerInternalFindRoute = (router: GlobalSearchRouter) => { router.post( { path: '/internal/global_search/find', diff --git a/x-pack/plugins/global_search/server/routes/get_searchable_types.ts b/x-pack/plugins/global_search/server/routes/get_searchable_types.ts index f9cc69e4a28ae..c2e58b0cd9ba7 100644 --- a/x-pack/plugins/global_search/server/routes/get_searchable_types.ts +++ b/x-pack/plugins/global_search/server/routes/get_searchable_types.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import { GlobalSearchRouter } from '../types'; -export const registerInternalSearchableTypesRoute = (router: IRouter) => { +export const registerInternalSearchableTypesRoute = (router: GlobalSearchRouter) => { router.get( { path: '/internal/global_search/searchable_types', diff --git a/x-pack/plugins/global_search/server/routes/index.ts b/x-pack/plugins/global_search/server/routes/index.ts index 0eeb443b72b53..7f11f01cbc46a 100644 --- a/x-pack/plugins/global_search/server/routes/index.ts +++ b/x-pack/plugins/global_search/server/routes/index.ts @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import { GlobalSearchRouter } from '../types'; import { registerInternalFindRoute } from './find'; import { registerInternalSearchableTypesRoute } from './get_searchable_types'; -export const registerRoutes = (router: IRouter) => { +export const registerRoutes = (router: GlobalSearchRouter) => { registerInternalFindRoute(router); registerInternalSearchableTypesRoute(router); }; diff --git a/x-pack/plugins/global_search/server/routes/integration_tests/find.test.ts b/x-pack/plugins/global_search/server/routes/integration_tests/find.test.ts index c37bcdbf84743..db46cdfff360c 100644 --- a/x-pack/plugins/global_search/server/routes/integration_tests/find.test.ts +++ b/x-pack/plugins/global_search/server/routes/integration_tests/find.test.ts @@ -41,13 +41,12 @@ describe('POST /internal/global_search/find', () => { ({ server, httpSetup } = await setupServer(pluginId)); globalSearchHandlerContext = globalSearchPluginMock.createRouteHandlerContext(); - httpSetup.registerRouteHandlerContext( - pluginId, - 'globalSearch', - () => globalSearchHandlerContext - ); + httpSetup.registerRouteHandlerContext< + ReturnType, + 'globalSearch' + >(pluginId, 'globalSearch', () => globalSearchHandlerContext); - const router = httpSetup.createRouter('/'); + const router = httpSetup.createRouter('/'); registerInternalFindRoute(router); diff --git a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts index b3b6862599d6d..66528e4fbe855 100644 --- a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts +++ b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts @@ -24,13 +24,14 @@ describe('GET /internal/global_search/searchable_types', () => { ({ server, httpSetup } = await setupServer(pluginId)); globalSearchHandlerContext = globalSearchPluginMock.createRouteHandlerContext(); - httpSetup.registerRouteHandlerContext( - pluginId, - 'globalSearch', - () => globalSearchHandlerContext - ); - - const router = httpSetup.createRouter('/'); + httpSetup.registerRouteHandlerContext< + ReturnType, + 'globalSearch' + >(pluginId, 'globalSearch', () => globalSearchHandlerContext); + + const router = httpSetup.createRouter< + ReturnType + >('/'); registerInternalSearchableTypesRoute(router); diff --git a/x-pack/plugins/global_search/server/types.ts b/x-pack/plugins/global_search/server/types.ts index 48c40fdb66e13..17b3505041f06 100644 --- a/x-pack/plugins/global_search/server/types.ts +++ b/x-pack/plugins/global_search/server/types.ts @@ -5,12 +5,14 @@ */ import { Observable } from 'rxjs'; -import { +import type { ISavedObjectTypeRegistry, ILegacyScopedClusterClient, IUiSettingsClient, SavedObjectsClientContract, Capabilities, + IRouter, + RequestHandlerContext, } from 'src/core/server'; import { GlobalSearchBatchedResults, @@ -24,6 +26,17 @@ import { SearchServiceSetup, SearchServiceStart } from './services'; export type GlobalSearchPluginSetup = Pick; export type GlobalSearchPluginStart = Pick; +/** + * @internal + */ +export interface GlobalSearchRequestHandlerContext extends RequestHandlerContext { + globalSearch: RouteHandlerGlobalSearchContext; +} + +/** + * @internal + */ +export type GlobalSearchRouter = IRouter; /** * globalSearch route handler context. * diff --git a/x-pack/plugins/index_management/server/plugin.ts b/x-pack/plugins/index_management/server/plugin.ts index 99facacacfe4c..3717e7e94d29f 100644 --- a/x-pack/plugins/index_management/server/plugin.ts +++ b/x-pack/plugins/index_management/server/plugin.ts @@ -4,19 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -declare module 'kibana/server' { - interface RequestHandlerContext { - dataManagement?: DataManagementContext; - } -} - import { i18n } from '@kbn/i18n'; import { CoreSetup, Plugin, Logger, PluginInitializerContext, - ILegacyScopedClusterClient, ILegacyCustomClusterClient, } from 'src/core/server'; @@ -26,10 +19,7 @@ import { ApiRoutes } from './routes'; import { License, IndexDataEnricher } from './services'; import { isEsError, handleEsError, parseEsError } from './shared_imports'; import { elasticsearchJsPlugin } from './client/elasticsearch'; - -export interface DataManagementContext { - client: ILegacyScopedClusterClient; -} +import type { IndexManagementRequestHandlerContext } from './types'; export interface IndexManagementPluginSetup { indexDataEnricher: { @@ -61,7 +51,7 @@ export class IndexMgmtServerPlugin implements Plugin(); this.license.setup( { @@ -92,14 +82,17 @@ export class IndexMgmtServerPlugin implements Plugin { - this.dataManagementESClient = - this.dataManagementESClient ?? (await getCustomEsClient(getStartServices)); + http.registerRouteHandlerContext( + 'dataManagement', + async (ctx, request) => { + this.dataManagementESClient = + this.dataManagementESClient ?? (await getCustomEsClient(getStartServices)); - return { - client: this.dataManagementESClient.asScoped(request), - }; - }); + return { + client: this.dataManagementESClient.asScoped(request), + }; + } + ); this.apiRoutes.setup({ router, diff --git a/x-pack/plugins/index_management/server/services/license.ts b/x-pack/plugins/index_management/server/services/license.ts index 9b68acd073c4a..22497a9d45ecd 100644 --- a/x-pack/plugins/index_management/server/services/license.ts +++ b/x-pack/plugins/index_management/server/services/license.ts @@ -4,15 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import { Logger } from 'src/core/server'; -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from 'kibana/server'; +import type { KibanaRequest, KibanaResponseFactory, RequestHandler } from 'kibana/server'; import { LicensingPluginSetup } from '../../../licensing/server'; import { LicenseType } from '../../../licensing/common/types'; +import type { IndexManagementRequestHandlerContext } from '../types'; export interface LicenseStatus { isValid: boolean; @@ -53,11 +49,13 @@ export class License { }); } - guardApiRoute(handler: RequestHandler) { + guardApiRoute( + handler: RequestHandler + ) { const license = this; return function licenseCheck( - ctx: RequestHandlerContext, + ctx: Context, request: KibanaRequest, response: KibanaResponseFactory ) { diff --git a/x-pack/plugins/index_management/server/types.ts b/x-pack/plugins/index_management/server/types.ts index 16a6b43af8512..34d03129c62d6 100644 --- a/x-pack/plugins/index_management/server/types.ts +++ b/x-pack/plugins/index_management/server/types.ts @@ -3,7 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { LegacyScopedClusterClient, IRouter } from 'src/core/server'; +import type { + LegacyScopedClusterClient, + ILegacyScopedClusterClient, + IRouter, + RequestHandlerContext, +} from 'src/core/server'; import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; import { LicensingPluginSetup } from '../../licensing/server'; import { SecurityPluginSetup } from '../../security/server'; @@ -17,7 +22,7 @@ export interface Dependencies { } export interface RouteDependencies { - router: IRouter; + router: IndexManagementRouter; license: License; config: { isSecurityEnabled: () => boolean; @@ -31,3 +36,26 @@ export interface RouteDependencies { } export type CallAsCurrentUser = LegacyScopedClusterClient['callAsCurrentUser']; + +export interface DataManagementContext { + client: ILegacyScopedClusterClient; +} + +/** + * @internal + */ +export interface IndexManagementApiRequestHandlerContext { + client: ILegacyScopedClusterClient; +} + +/** + * @internal + */ +export interface IndexManagementRequestHandlerContext extends RequestHandlerContext { + dataManagement: IndexManagementApiRequestHandlerContext; +} + +/** + * @internal + */ +export type IndexManagementRouter = IRouter; diff --git a/x-pack/plugins/infra/server/lib/adapters/fields/adapter_types.ts b/x-pack/plugins/infra/server/lib/adapters/fields/adapter_types.ts index a1630281c2f75..d6b069997b618 100644 --- a/x-pack/plugins/infra/server/lib/adapters/fields/adapter_types.ts +++ b/x-pack/plugins/infra/server/lib/adapters/fields/adapter_types.ts @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; export interface FieldsAdapter { getIndexFields( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, indices: string ): Promise; } diff --git a/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts index 8a9389ed585eb..57345f1353e91 100644 --- a/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { KibanaFramework } from '../framework/kibana_framework_adapter'; import { FieldsAdapter, IndexFieldDescriptor } from './adapter_types'; @@ -16,7 +16,7 @@ export class FrameworkFieldsAdapter implements FieldsAdapter { } public async getIndexFields( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, indices: string ): Promise { const indexPatternsService = this.framework.getIndexPatternsService(requestContext); diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts index 7f686b4d7717c..b96b0e5bb0b48 100644 --- a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -23,16 +23,16 @@ import { CoreSetup, IRouter, KibanaRequest, - RequestHandlerContext, KibanaResponseFactory, RouteMethod, } from '../../../../../../../src/core/server'; import { RequestHandler } from '../../../../../../../src/core/server'; import { InfraConfig } from '../../../plugin'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { IndexPatternsFetcher, UI_SETTINGS } from '../../../../../../../src/plugins/data/server'; export class KibanaFramework { - public router: IRouter; + public router: IRouter; public plugins: InfraServerPluginSetupDeps; constructor(core: CoreSetup, config: InfraConfig, plugins: InfraServerPluginSetupDeps) { @@ -42,7 +42,7 @@ export class KibanaFramework { public registerRoute( config: InfraRouteConfig, - handler: RequestHandler + handler: RequestHandler ) { const defaultOptions = { tags: ['access:infra'], @@ -88,7 +88,7 @@ export class KibanaFramework { }, }; async function handler( - context: RequestHandlerContext, + context: InfraPluginRequestHandlerContext, request: KibanaRequest, response: KibanaResponseFactory ) { @@ -100,7 +100,7 @@ export class KibanaFramework { const gqlResponse = await runHttpQuery([context, request], { method: request.route.method.toUpperCase(), - options: (req: RequestHandlerContext, rawReq: KibanaRequest) => ({ + options: (req: InfraPluginRequestHandlerContext, rawReq: KibanaRequest) => ({ context: { req, rawReq }, schema: gqlSchema, }), @@ -147,48 +147,48 @@ export class KibanaFramework { } callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, endpoint: 'search', options?: CallWithRequestParams ): Promise>; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, endpoint: 'msearch', options?: CallWithRequestParams ): Promise>; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, endpoint: 'fieldCaps', options?: CallWithRequestParams ): Promise; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, endpoint: 'indices.existsAlias', options?: CallWithRequestParams ): Promise; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, method: 'indices.getAlias', options?: object ): Promise; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, method: 'indices.get' | 'ml.getBuckets', options?: object ): Promise; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, method: 'transport.request', options?: CallWithRequestParams ): Promise; callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, endpoint: string, options?: CallWithRequestParams ): Promise; public async callWithRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, endpoint: string, params: CallWithRequestParams ) { @@ -216,7 +216,9 @@ export class KibanaFramework { }); } - public getIndexPatternsService(requestContext: RequestHandlerContext): IndexPatternsFetcher { + public getIndexPatternsService( + requestContext: InfraPluginRequestHandlerContext + ): IndexPatternsFetcher { return new IndexPatternsFetcher(requestContext.core.elasticsearch.client.asCurrentUser, true); } @@ -235,7 +237,7 @@ export class KibanaFramework { } public async makeTSVBRequest( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, rawRequest: KibanaRequest, model: TSVBMetricModel, timerange: { min: number; max: number }, diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index 98c42ab7d98ab..ffbc750af14f8 100644 --- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -10,8 +10,8 @@ import { constant, identity } from 'fp-ts/lib/function'; import { pipe } from 'fp-ts/lib/pipeable'; import * as runtimeTypes from 'io-ts'; import { compact } from 'lodash'; -import { RequestHandlerContext } from 'src/core/server'; import { JsonArray } from '../../../../../../../src/plugins/kibana_utils/common'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { LogEntriesAdapter, LogEntriesParams, @@ -30,7 +30,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { constructor(private readonly framework: KibanaFramework) {} public async getLogEntries( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, fields: string[], params: LogEntriesParams @@ -123,7 +123,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { } public async getContainedLogSummaryBuckets( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, startTimestamp: number, endTimestamp: number, diff --git a/x-pack/plugins/infra/server/lib/adapters/metrics/adapter_types.ts b/x-pack/plugins/infra/server/lib/adapters/metrics/adapter_types.ts index f786c043ee27c..e20f1ab05fd56 100644 --- a/x-pack/plugins/infra/server/lib/adapters/metrics/adapter_types.ts +++ b/x-pack/plugins/infra/server/lib/adapters/metrics/adapter_types.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext, KibanaRequest } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { NodeDetailsRequest, NodeDetailsMetricData, @@ -23,7 +24,7 @@ export interface InfraMetricsRequestOptions export interface InfraMetricsAdapter { getMetrics( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, options: InfraMetricsRequestOptions, request: KibanaRequest ): Promise; diff --git a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts index 5718d49ae79d6..2c7d79b1c64d0 100644 --- a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts @@ -6,7 +6,7 @@ import { i18n } from '@kbn/i18n'; import { flatten, get } from 'lodash'; -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; import { NodeDetailsMetricData } from '../../../../common/http_api/node_details_api'; import { KibanaFramework } from '../framework/kibana_framework_adapter'; import { InfraMetricsAdapter, InfraMetricsRequestOptions } from './adapter_types'; @@ -19,6 +19,7 @@ import { } from '../../../../common/inventory_models/types'; import { calculateMetricInterval } from '../../../utils/calculate_metric_interval'; import { CallWithRequestParams, InfraDatabaseSearchResponse } from '../framework'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; export class KibanaMetricsAdapter implements InfraMetricsAdapter { private framework: KibanaFramework; @@ -28,7 +29,7 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { } public async getMetrics( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, options: InfraMetricsRequestOptions, rawRequest: KibanaRequest ): Promise { @@ -94,7 +95,7 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { metricId: InventoryMetric, options: InfraMetricsRequestOptions, nodeField: string, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, rawRequest: KibanaRequest ) { const createTSVBModel = get(metrics, ['tsvb', metricId]) as TSVBMetricModelCreator | undefined; diff --git a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts index 2a61e64c94fcd..cfa001788246c 100644 --- a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { InfraSourceStatusAdapter, SourceIndexStatus } from '../../source_status'; import { InfraDatabaseGetIndicesResponse } from '../framework'; import { KibanaFramework } from '../framework/kibana_framework_adapter'; @@ -12,7 +12,7 @@ import { KibanaFramework } from '../framework/kibana_framework_adapter'; export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusAdapter { constructor(private readonly framework: KibanaFramework) {} - public async getIndexNames(requestContext: RequestHandlerContext, aliasName: string) { + public async getIndexNames(requestContext: InfraPluginRequestHandlerContext, aliasName: string) { const indexMaps = await Promise.all([ this.framework .callWithRequest(requestContext, 'indices.getAlias', { @@ -34,14 +34,14 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA ); } - public async hasAlias(requestContext: RequestHandlerContext, aliasName: string) { + public async hasAlias(requestContext: InfraPluginRequestHandlerContext, aliasName: string) { return await this.framework.callWithRequest(requestContext, 'indices.existsAlias', { name: aliasName, }); } public async getIndexStatus( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, indexNames: string ): Promise { return await this.framework diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_chart_preview.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_chart_preview.ts index e1657968b3f92..0ecea1f5db32e 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_chart_preview.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_chart_preview.ts @@ -5,7 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { InfraSource } from '../../sources'; import { KibanaFramework } from '../../adapters/framework/kibana_framework_adapter'; import { @@ -29,7 +29,7 @@ import { decodeOrThrow } from '../../../../common/runtime_types'; const COMPOSITE_GROUP_SIZE = 40; export async function getChartPreviewData( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSource, callWithRequest: KibanaFramework['callWithRequest'], alertParams: GetLogAlertsChartPreviewDataAlertParamsSubset, @@ -114,7 +114,7 @@ const addHistogramAggregationToQuery = ( const getUngroupedResults = async ( query: object, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, callWithRequest: KibanaFramework['callWithRequest'] ) => { return decodeOrThrow(UngroupedSearchQueryResponseRT)( @@ -124,7 +124,7 @@ const getUngroupedResults = async ( const getGroupedResults = async ( query: object, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, callWithRequest: KibanaFramework['callWithRequest'] ) => { let compositeGroupBuckets: GroupedSearchQueryResponse['aggregations']['groups']['buckets'] = []; diff --git a/x-pack/plugins/infra/server/lib/create_search_client.ts b/x-pack/plugins/infra/server/lib/create_search_client.ts index d79d20b502e94..cc354754c3403 100644 --- a/x-pack/plugins/infra/server/lib/create_search_client.ts +++ b/x-pack/plugins/infra/server/lib/create_search_client.ts @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../types'; import { CallWithRequestParams, InfraDatabaseSearchResponse } from './adapters/framework'; import { KibanaFramework } from './adapters/framework/kibana_framework_adapter'; export const createSearchClient = ( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, framework: KibanaFramework ) => ( opts: CallWithRequestParams diff --git a/x-pack/plugins/infra/server/lib/domains/fields_domain.ts b/x-pack/plugins/infra/server/lib/domains/fields_domain.ts index ecbc71f4895c7..a8bd09c28f949 100644 --- a/x-pack/plugins/infra/server/lib/domains/fields_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/fields_domain.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../types'; import { InfraIndexField, InfraIndexType } from '../../graphql/types'; import { FieldsAdapter } from '../adapters/fields'; import { InfraSources } from '../sources'; @@ -16,7 +16,7 @@ export class InfraFieldsDomain { ) {} public async getFields( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string, indexType: InfraIndexType ): Promise { diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts index d9f125908b32d..0b1df3abd465a 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -4,8 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; import { JsonObject } from '../../../../../../../src/plugins/kibana_utils/common'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; + import { LogEntriesSummaryBucket, LogEntriesSummaryHighlightsBucket, @@ -68,7 +69,7 @@ export class InfraLogEntriesDomain { ) {} public async getLogEntriesAround( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string, params: LogEntriesAroundParams, columnOverrides?: LogEntriesRequest['columns'] @@ -128,7 +129,7 @@ export class InfraLogEntriesDomain { } public async getLogEntries( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string, params: LogEntriesParams, columnOverrides?: LogEntriesRequest['columns'] @@ -187,7 +188,7 @@ export class InfraLogEntriesDomain { } public async getLogSummaryBucketsBetween( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string, start: number, end: number, @@ -210,7 +211,7 @@ export class InfraLogEntriesDomain { } public async getLogSummaryHighlightBucketsBetween( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string, startTimestamp: number, endTimestamp: number, @@ -256,7 +257,7 @@ export class InfraLogEntriesDomain { } public async getLogEntryDatasets( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, timestampField: string, indexName: string, startTime: number, @@ -297,14 +298,14 @@ export class InfraLogEntriesDomain { export interface LogEntriesAdapter { getLogEntries( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, fields: string[], params: LogEntriesParams ): Promise<{ documents: LogEntryDocument[]; hasMoreBefore?: boolean; hasMoreAfter?: boolean }>; getContainedLogSummaryBuckets( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, startTimestamp: number, endTimestamp: number, diff --git a/x-pack/plugins/infra/server/lib/domains/metrics_domain.ts b/x-pack/plugins/infra/server/lib/domains/metrics_domain.ts index ac76e264ff0ed..0189fa885af0e 100644 --- a/x-pack/plugins/infra/server/lib/domains/metrics_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/metrics_domain.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../types'; import { InfraMetricsAdapter, InfraMetricsRequestOptions } from '../adapters/metrics/adapter_types'; import { NodeDetailsMetricData } from '../../../common/http_api/node_details_api'; @@ -16,7 +17,7 @@ export class InfraMetricsDomain { } public async getMetrics( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, options: InfraMetricsRequestOptions, rawRequest: KibanaRequest ): Promise { diff --git a/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts b/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts index c8278bd308758..6d6ac68a4d412 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../types'; import { InfraRequestHandlerContext } from '../../types'; import { TracingSpan, startTracingSpan } from '../../../common/performance_tracing'; import { fetchMlJob } from './common'; @@ -73,7 +73,7 @@ async function getCompatibleAnomaliesJobIds( } export async function getMetricsHostsAnomalies( - context: RequestHandlerContext & { infra: Required }, + context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, startTime: number, endTime: number, diff --git a/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts b/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts index c8427ef489c4c..6d8ac7fa00d55 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../types'; import { InfraRequestHandlerContext } from '../../types'; import { TracingSpan, startTracingSpan } from '../../../common/performance_tracing'; import { fetchMlJob } from './common'; @@ -73,7 +73,7 @@ async function getCompatibleAnomaliesJobIds( } export async function getMetricK8sAnomalies( - context: RequestHandlerContext & { infra: Required }, + context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, startTime: number, endTime: number, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts index 44731fe465d26..c6a4593912280 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; -import { InfraRequestHandlerContext } from '../../types'; +import type { InfraPluginRequestHandlerContext, InfraRequestHandlerContext } from '../../types'; import { TracingSpan, startTracingSpan } from '../../../common/performance_tracing'; import { fetchMlJob, getLogEntryDatasets } from './common'; import { @@ -92,7 +91,7 @@ async function getCompatibleAnomaliesJobIds( } export async function getLogEntryAnomalies( - context: RequestHandlerContext & { infra: Required }, + context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, startTime: number, endTime: number, @@ -291,7 +290,7 @@ async function fetchLogEntryAnomalies( } export async function getLogEntryExamples( - context: RequestHandlerContext & { infra: Required }, + context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, startTime: number, endTime: number, @@ -353,7 +352,7 @@ export async function getLogEntryExamples( } export async function fetchLogEntryExamples( - context: RequestHandlerContext & { infra: Required }, + context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, indices: string, timestampField: string, diff --git a/x-pack/plugins/infra/server/lib/source_status.ts b/x-pack/plugins/infra/server/lib/source_status.ts index c383d01933562..5bfeff23f9aea 100644 --- a/x-pack/plugins/infra/server/lib/source_status.ts +++ b/x-pack/plugins/infra/server/lib/source_status.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../types'; import { InfraSources } from './sources'; export class InfraSourceStatus { @@ -14,7 +14,7 @@ export class InfraSourceStatus { ) {} public async getLogIndexNames( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( @@ -28,7 +28,7 @@ export class InfraSourceStatus { return indexNames; } public async getMetricIndexNames( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( @@ -42,7 +42,7 @@ export class InfraSourceStatus { return indexNames; } public async hasLogAlias( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( @@ -56,7 +56,7 @@ export class InfraSourceStatus { return hasAlias; } public async hasMetricAlias( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( @@ -70,7 +70,7 @@ export class InfraSourceStatus { return hasAlias; } public async getLogIndexStatus( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( @@ -84,7 +84,7 @@ export class InfraSourceStatus { return indexStatus; } public async hasMetricIndices( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceId: string ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( @@ -102,10 +102,13 @@ export class InfraSourceStatus { export type SourceIndexStatus = 'missing' | 'empty' | 'available'; export interface InfraSourceStatusAdapter { - getIndexNames(requestContext: RequestHandlerContext, aliasName: string): Promise; - hasAlias(requestContext: RequestHandlerContext, aliasName: string): Promise; + getIndexNames( + requestContext: InfraPluginRequestHandlerContext, + aliasName: string + ): Promise; + hasAlias(requestContext: InfraPluginRequestHandlerContext, aliasName: string): Promise; getIndexStatus( - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, indexNames: string ): Promise; } diff --git a/x-pack/plugins/infra/server/plugin.ts b/x-pack/plugins/infra/server/plugin.ts index 693e98521ada2..207c2efa0f13f 100644 --- a/x-pack/plugins/infra/server/plugin.ts +++ b/x-pack/plugins/infra/server/plugin.ts @@ -28,7 +28,7 @@ import { InfraBackendLibs, InfraDomainLibs } from './lib/infra_types'; import { infraSourceConfigurationSavedObjectType, InfraSources } from './lib/sources'; import { InfraSourceStatus } from './lib/source_status'; import { LogEntriesService } from './services/log_entries'; -import { InfraRequestHandlerContext } from './types'; +import { InfraPluginRequestHandlerContext } from './types'; import { UsageCollector } from './usage/usage_collector'; export const config = { @@ -146,9 +146,9 @@ export class InfraServerPlugin { initInfraServer(this.libs); registerAlertTypes(plugins.alerts, this.libs); - core.http.registerRouteHandlerContext( + core.http.registerRouteHandlerContext( 'infra', - (context, request): InfraRequestHandlerContext => { + (context, request) => { const mlSystem = plugins.ml?.mlSystemProvider(request, context.core.savedObjects.client); const mlAnomalyDetectors = plugins.ml?.anomalyDetectorsProvider( request, diff --git a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts index af9e9c5f57c5b..2be812043a0c0 100644 --- a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts +++ b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'kibana/server'; import { InventoryCloudAccount } from '../../../../common/http_api/inventory_meta_api'; import { InfraMetadataAggregationResponse, @@ -14,6 +13,7 @@ import { InfraSourceConfiguration } from '../../../lib/sources'; import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framework_adapter'; import { InventoryItemType } from '../../../../common/inventory_models/types'; import { findInventoryModel } from '../../../../common/inventory_models'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; export interface CloudMetaData { accounts: InventoryCloudAccount[]; @@ -23,7 +23,7 @@ export interface CloudMetaData { export const getCloudMetadata = async ( framework: KibanaFramework, - req: RequestHandlerContext, + req: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, nodeType: InventoryItemType, currentTime: number diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts index 82427a833a20c..57d8fb9eb9509 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { InfraMetadataAggregationBucket, InfraMetadataAggregationResponse, @@ -19,7 +19,7 @@ export interface InfraCloudMetricsAdapterResponse { export const getCloudMetricsMetadata = async ( framework: KibanaFramework, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, instanceId: string, timeRange: { from: number; to: number } diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts index 7753d3161039b..d1dec098af118 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts @@ -5,7 +5,7 @@ */ import { get } from 'lodash'; -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { InfraMetadataAggregationBucket, InfraMetadataAggregationResponse, @@ -23,7 +23,7 @@ export interface InfraMetricsAdapterResponse { export const getMetricMetadata = async ( framework: KibanaFramework, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, nodeId: string, nodeType: InventoryItemType, diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts index b378b42e2ff59..21ef61a55e35f 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts @@ -6,7 +6,7 @@ import { set } from '@elastic/safer-lodash-set'; import { first, startsWith } from 'lodash'; -import { RequestHandlerContext } from 'src/core/server'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framework_adapter'; import { InfraSourceConfiguration } from '../../../lib/sources'; import { InfraMetadataInfo } from '../../../../common/http_api/metadata_api'; @@ -17,7 +17,7 @@ import { InventoryItemType } from '../../../../common/inventory_models/types'; export const getNodeInfo = async ( framework: KibanaFramework, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, nodeId: string, nodeType: InventoryItemType, diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts index b4656178d395e..e52976519ef48 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts @@ -5,14 +5,14 @@ */ import { first, get } from 'lodash'; -import { RequestHandlerContext } from 'src/core/server'; import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framework_adapter'; import { InfraSourceConfiguration } from '../../../lib/sources'; import { findInventoryFields } from '../../../../common/inventory_models'; +import type { InfraPluginRequestHandlerContext } from '../../../types'; export const getPodNodeName = async ( framework: KibanaFramework, - requestContext: RequestHandlerContext, + requestContext: InfraPluginRequestHandlerContext, sourceConfiguration: InfraSourceConfiguration, nodeId: string, nodeType: 'host' | 'pod' | 'container', diff --git a/x-pack/plugins/infra/server/types.ts b/x-pack/plugins/infra/server/types.ts index 735569a790f64..2a30bf7cf093d 100644 --- a/x-pack/plugins/infra/server/types.ts +++ b/x-pack/plugins/infra/server/types.ts @@ -3,7 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import type { RequestHandlerContext } from 'src/core/server'; +import type { DataApiRequestHandlerContext } from '../../../../src/plugins/data/server'; import { MlPluginSetup } from '../../ml/server'; export type MlSystem = ReturnType; @@ -21,8 +22,10 @@ export interface InfraSpacesRequestHandlerContext { export type InfraRequestHandlerContext = InfraMlRequestHandlerContext & InfraSpacesRequestHandlerContext; -declare module 'src/core/server' { - interface RequestHandlerContext { - infra?: InfraRequestHandlerContext; - } +/** + * @internal + */ +export interface InfraPluginRequestHandlerContext extends RequestHandlerContext { + infra: InfraRequestHandlerContext; + search: DataApiRequestHandlerContext; } diff --git a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts index 6d16e045d26d5..19169957f4c50 100644 --- a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts +++ b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -// import { RequestHandlerContext } from 'src/core/server'; import { findInventoryModel } from '../../common/inventory_models'; // import { KibanaFramework } from '../lib/adapters/framework/kibana_framework_adapter'; import { InventoryItemType } from '../../common/inventory_models/types'; diff --git a/x-pack/plugins/licensing/server/licensing_route_handler_context.ts b/x-pack/plugins/licensing/server/licensing_route_handler_context.ts index 736a2151a3dbd..0a85d6a8ff890 100644 --- a/x-pack/plugins/licensing/server/licensing_route_handler_context.ts +++ b/x-pack/plugins/licensing/server/licensing_route_handler_context.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IContextProvider, RequestHandler, StartServicesAccessor } from 'src/core/server'; +import type { IContextProvider, StartServicesAccessor } from 'src/core/server'; import { Observable } from 'rxjs'; import { take } from 'rxjs/operators'; -import { ILicense } from '../common/types'; -import { LicensingPluginStart } from './types'; +import type { ILicense } from '../common/types'; +import type { LicensingPluginStart, LicensingRequestHandlerContext } from './types'; /** * Create a route handler context for access to Kibana license information. @@ -19,7 +19,7 @@ import { LicensingPluginStart } from './types'; export function createRouteHandlerContext( license$: Observable, getStartServices: StartServicesAccessor<{}, LicensingPluginStart> -): IContextProvider, 'licensing'> { +): IContextProvider { return async function licensingRouteHandlerContext() { const [, , { featureUsage }] = await getStartServices(); const license = await license$.pipe(take(1)).toPromise(); diff --git a/x-pack/plugins/licensing/server/mocks.ts b/x-pack/plugins/licensing/server/mocks.ts index 1a2b543b47df5..cab1823f22ac4 100644 --- a/x-pack/plugins/licensing/server/mocks.ts +++ b/x-pack/plugins/licensing/server/mocks.ts @@ -7,7 +7,7 @@ import { BehaviorSubject } from 'rxjs'; import { LicensingPluginSetup, LicensingPluginStart, - LicensingRequestHandlerContext, + LicensingApiRequestHandlerContext, } from './types'; import { licenseMock } from '../common/licensing.mock'; import { featureUsageMock } from './services/feature_usage_service.mock'; @@ -49,8 +49,8 @@ const createStartMock = (): jest.Mocked => { const createRequestHandlerContextMock = ( ...options: Parameters -): jest.Mocked => { - const mock: jest.Mocked = { +): jest.Mocked => { + const mock: jest.Mocked = { license: licenseMock.createLicense(...options), featureUsage: featureUsageMock.createStart(), }; diff --git a/x-pack/plugins/licensing/server/routes/feature_usage.ts b/x-pack/plugins/licensing/server/routes/feature_usage.ts index fa26d09903dc3..da4853145c338 100644 --- a/x-pack/plugins/licensing/server/routes/feature_usage.ts +++ b/x-pack/plugins/licensing/server/routes/feature_usage.ts @@ -3,11 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { IRouter, StartServicesAccessor } from 'src/core/server'; +import { StartServicesAccessor } from 'src/core/server'; import { LicensingPluginStart } from '../types'; +import { LicensingRouter } from '../types'; export function registerFeatureUsageRoute( - router: IRouter, + router: LicensingRouter, getStartServices: StartServicesAccessor<{}, LicensingPluginStart> ) { router.get( diff --git a/x-pack/plugins/licensing/server/routes/index.ts b/x-pack/plugins/licensing/server/routes/index.ts index 16065d8e19adc..3a86653c6cb4a 100644 --- a/x-pack/plugins/licensing/server/routes/index.ts +++ b/x-pack/plugins/licensing/server/routes/index.ts @@ -4,15 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter, StartServicesAccessor } from 'src/core/server'; +import { StartServicesAccessor } from 'src/core/server'; import { LicensingPluginStart } from '../types'; import { FeatureUsageServiceSetup } from '../services'; import { registerInfoRoute } from './info'; import { registerFeatureUsageRoute } from './feature_usage'; import { registerNotifyFeatureUsageRoute, registerRegisterFeatureRoute } from './internal'; +import { LicensingRouter } from '../types'; export function registerRoutes( - router: IRouter, + router: LicensingRouter, featureUsageSetup: FeatureUsageServiceSetup, getStartServices: StartServicesAccessor<{}, LicensingPluginStart> ) { diff --git a/x-pack/plugins/licensing/server/routes/info.ts b/x-pack/plugins/licensing/server/routes/info.ts index cad873014e271..c07649bf1b12f 100644 --- a/x-pack/plugins/licensing/server/routes/info.ts +++ b/x-pack/plugins/licensing/server/routes/info.ts @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import { LicensingRouter } from '../types'; -export function registerInfoRoute(router: IRouter) { +export function registerInfoRoute(router: LicensingRouter) { router.get({ path: '/api/licensing/info', validate: false }, (context, request, response) => { return response.ok({ body: context.licensing.license, diff --git a/x-pack/plugins/licensing/server/routes/internal/notify_feature_usage.ts b/x-pack/plugins/licensing/server/routes/internal/notify_feature_usage.ts index ec70472574be3..552126bff17b6 100644 --- a/x-pack/plugins/licensing/server/routes/internal/notify_feature_usage.ts +++ b/x-pack/plugins/licensing/server/routes/internal/notify_feature_usage.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import { LicensingRouter } from '../../types'; -export function registerNotifyFeatureUsageRoute(router: IRouter) { +export function registerNotifyFeatureUsageRoute(router: LicensingRouter) { router.post( { path: '/internal/licensing/feature_usage/notify', diff --git a/x-pack/plugins/licensing/server/routes/internal/register_feature.ts b/x-pack/plugins/licensing/server/routes/internal/register_feature.ts index 418e98fc1b2a8..750dc29ed273e 100644 --- a/x-pack/plugins/licensing/server/routes/internal/register_feature.ts +++ b/x-pack/plugins/licensing/server/routes/internal/register_feature.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; import { LicenseType, LICENSE_TYPE } from '../../../common/types'; import { FeatureUsageServiceSetup } from '../../services'; +import { LicensingRouter } from '../../types'; export function registerRegisterFeatureRoute( - router: IRouter, + router: LicensingRouter, featureUsageSetup: FeatureUsageServiceSetup ) { router.post( diff --git a/x-pack/plugins/licensing/server/types.ts b/x-pack/plugins/licensing/server/types.ts index dd1277429eabd..1c7fc69653682 100644 --- a/x-pack/plugins/licensing/server/types.ts +++ b/x-pack/plugins/licensing/server/types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import { Observable } from 'rxjs'; -import { ILegacyClusterClient } from 'src/core/server'; +import type { ILegacyClusterClient, IRouter, RequestHandlerContext } from 'src/core/server'; import { ILicense, LicenseStatus, LicenseType } from '../common/types'; import { FeatureUsageServiceSetup, FeatureUsageServiceStart } from './services'; @@ -44,17 +44,23 @@ export interface RawLicense { * The APIs exposed on the `licensing` key of {@link RequestHandlerContext} for plugins that depend on licensing. * @public */ -export interface LicensingRequestHandlerContext { +export interface LicensingApiRequestHandlerContext { featureUsage: FeatureUsageServiceStart; license: ILicense; } -declare module 'src/core/server' { - interface RequestHandlerContext { - licensing: LicensingRequestHandlerContext; - } +/** + * @internal + */ +export interface LicensingRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; } +/** + * @internal + */ +export type LicensingRouter = IRouter; + /** @public */ export interface LicensingPluginSetup { /** diff --git a/x-pack/plugins/licensing/server/wrap_route_with_license_check.ts b/x-pack/plugins/licensing/server/wrap_route_with_license_check.ts index e0cac8d9db208..188c8dbf27157 100644 --- a/x-pack/plugins/licensing/server/wrap_route_with_license_check.ts +++ b/x-pack/plugins/licensing/server/wrap_route_with_license_check.ts @@ -4,26 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - RequestHandler, - RequestHandlerContext, - KibanaRequest, - RouteMethod, - KibanaResponseFactory, -} from 'src/core/server'; +import { RequestHandler, KibanaRequest, RouteMethod, KibanaResponseFactory } from 'src/core/server'; import { ILicense } from '../common/types'; +import type { LicensingRequestHandlerContext } from './types'; export type CheckLicense = ( license: ILicense ) => { valid: false; message: string } | { valid: true; message: null }; -export function wrapRouteWithLicenseCheck( +export function wrapRouteWithLicenseCheck( checkLicense: CheckLicense, - handler: RequestHandler -): RequestHandler { + handler: RequestHandler +): RequestHandler { return async ( - context: RequestHandlerContext, + context: Context, request: KibanaRequest, response: KibanaResponseFactory ) => { diff --git a/x-pack/plugins/lists/server/index.ts b/x-pack/plugins/lists/server/index.ts index ea27073e3053d..2738736d62a3d 100644 --- a/x-pack/plugins/lists/server/index.ts +++ b/x-pack/plugins/lists/server/index.ts @@ -13,7 +13,7 @@ import { ListPlugin } from './plugin'; export { ListClient } from './services/lists/list_client'; export { CreateExceptionListItemOptions } from './services/exception_lists/exception_list_client_types'; export { ExceptionListClient } from './services/exception_lists/exception_list_client'; -export { ListPluginSetup } from './types'; +export type { ListPluginSetup, ListsApiRequestHandlerContext } from './types'; export const config = { schema: ConfigSchema }; export const plugin = (initializerContext: PluginInitializerContext): ListPlugin => diff --git a/x-pack/plugins/lists/server/plugin.ts b/x-pack/plugins/lists/server/plugin.ts index 670f0fe684cc2..c6d42e5ac4f23 100644 --- a/x-pack/plugins/lists/server/plugin.ts +++ b/x-pack/plugins/lists/server/plugin.ts @@ -19,6 +19,7 @@ import type { ContextProviderReturn, ListPluginSetup, ListsPluginStart, + ListsRequestHandlerContext, PluginsStart, } from './types'; import { createConfig$ } from './create_config'; @@ -44,8 +45,11 @@ export class ListPlugin initSavedObjects(core.savedObjects); - core.http.registerRouteHandlerContext('lists', this.createRouteHandlerContext()); - const router = core.http.createRouter(); + core.http.registerRouteHandlerContext( + 'lists', + this.createRouteHandlerContext() + ); + const router = core.http.createRouter(); initRoutes(router, config); return { diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts index cce4038ff48d6..86072b18db658 100644 --- a/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ENDPOINT_LIST_ID, ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -18,7 +17,7 @@ import { import { getExceptionListClient } from './utils/get_exception_list_client'; import { validateExceptionListSize } from './validate'; -export const createEndpointListItemRoute = (router: IRouter): void => { +export const createEndpointListItemRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts b/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts index 91b6a328c8649..51f647d76f403 100644 --- a/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts +++ b/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ENDPOINT_LIST_URL } from '../../common/constants'; import { buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -22,7 +21,7 @@ import { getExceptionListClient } from './utils/get_exception_list_client'; * object. * @param router The router to use. */ -export const createEndpointListRoute = (router: IRouter): void => { +export const createEndpointListRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts index afcb0f99c8a35..b0456e13d15df 100644 --- a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -19,7 +18,7 @@ import { getExceptionListClient } from './utils/get_exception_list_client'; import { endpointDisallowedFields } from './endpoint_disallowed_fields'; import { validateEndpointExceptionItemEntries, validateExceptionListSize } from './validate'; -export const createExceptionListItemRoute = (router: IRouter): void => { +export const createExceptionListItemRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/create_exception_list_route.ts b/x-pack/plugins/lists/server/routes/create_exception_list_route.ts index fd2ba6340009c..506b70c92357c 100644 --- a/x-pack/plugins/lists/server/routes/create_exception_list_route.ts +++ b/x-pack/plugins/lists/server/routes/create_exception_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getExceptionListClient } from './utils/get_exception_list_client'; -export const createExceptionListRoute = (router: IRouter): void => { +export const createExceptionListRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/create_list_index_route.ts b/x-pack/plugins/lists/server/routes/create_list_index_route.ts index be08093dc7055..bca6f1d085eb0 100644 --- a/x-pack/plugins/lists/server/routes/create_list_index_route.ts +++ b/x-pack/plugins/lists/server/routes/create_list_index_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; import { LIST_INDEX } from '../../common/constants'; @@ -13,7 +12,7 @@ import { acknowledgeSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const createListIndexRoute = (router: IRouter): void => { +export const createListIndexRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/create_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_list_item_route.ts index bd2828d331d83..50d7b141ddeff 100644 --- a/x-pack/plugins/lists/server/routes/create_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/create_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { createListItemSchema, listItemSchema } from '../../common/schemas'; @@ -13,7 +12,7 @@ import { validate } from '../../common/shared_imports'; import { getListClient } from '.'; -export const createListItemRoute = (router: IRouter): void => { +export const createListItemRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/create_list_route.ts b/x-pack/plugins/lists/server/routes/create_list_route.ts index 90f5bf9b2c650..49749bbab9044 100644 --- a/x-pack/plugins/lists/server/routes/create_list_route.ts +++ b/x-pack/plugins/lists/server/routes/create_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { CreateListSchemaDecoded, createListSchema, listSchema } from '../../com import { getListClient } from '.'; -export const createListRoute = (router: IRouter): void => { +export const createListRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts index 380fdcf862060..c8367561711f6 100644 --- a/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionListItem, getExceptionListClient } from './utils'; -export const deleteEndpointListItemRoute = (router: IRouter): void => { +export const deleteEndpointListItemRoute = (router: ListsPluginRouter): void => { router.delete( { options: { diff --git a/x-pack/plugins/lists/server/routes/delete_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/delete_exception_list_item_route.ts index 07e0fad20c900..fd313f48e1cc6 100644 --- a/x-pack/plugins/lists/server/routes/delete_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/delete_exception_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionListItem, getExceptionListClient } from './utils'; -export const deleteExceptionListItemRoute = (router: IRouter): void => { +export const deleteExceptionListItemRoute = (router: ListsPluginRouter): void => { router.delete( { options: { diff --git a/x-pack/plugins/lists/server/routes/delete_exception_list_route.ts b/x-pack/plugins/lists/server/routes/delete_exception_list_route.ts index 769ce732240b7..ae9078de1af9b 100644 --- a/x-pack/plugins/lists/server/routes/delete_exception_list_route.ts +++ b/x-pack/plugins/lists/server/routes/delete_exception_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionList, getExceptionListClient } from './utils'; -export const deleteExceptionListRoute = (router: IRouter): void => { +export const deleteExceptionListRoute = (router: ListsPluginRouter): void => { router.delete( { options: { diff --git a/x-pack/plugins/lists/server/routes/delete_list_index_route.ts b/x-pack/plugins/lists/server/routes/delete_list_index_route.ts index aa587273036ae..5e2b4cc2a9413 100644 --- a/x-pack/plugins/lists/server/routes/delete_list_index_route.ts +++ b/x-pack/plugins/lists/server/routes/delete_list_index_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_INDEX } from '../../common/constants'; import { buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -29,7 +28,7 @@ import { getListClient } from '.'; * * And ensuring they're all gone */ -export const deleteListIndexRoute = (router: IRouter): void => { +export const deleteListIndexRoute = (router: ListsPluginRouter): void => { router.delete( { options: { diff --git a/x-pack/plugins/lists/server/routes/delete_list_item_route.ts b/x-pack/plugins/lists/server/routes/delete_list_item_route.ts index fa1adf8a39ed8..673520ec59e30 100644 --- a/x-pack/plugins/lists/server/routes/delete_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/delete_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { deleteListItemSchema, listItemArraySchema, listItemSchema } from '../.. import { getListClient } from '.'; -export const deleteListItemRoute = (router: IRouter): void => { +export const deleteListItemRoute = (router: ListsPluginRouter): void => { router.delete( { options: { diff --git a/x-pack/plugins/lists/server/routes/delete_list_route.ts b/x-pack/plugins/lists/server/routes/delete_list_route.ts index bf8fac7f3dd8c..bf411247b74d5 100644 --- a/x-pack/plugins/lists/server/routes/delete_list_route.ts +++ b/x-pack/plugins/lists/server/routes/delete_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -22,7 +21,7 @@ import { ExceptionListClient } from '../services/exception_lists/exception_list_ import { getExceptionListClient, getListClient } from '.'; -export const deleteListRoute = (router: IRouter): void => { +export const deleteListRoute = (router: ListsPluginRouter): void => { router.delete( { options: { diff --git a/x-pack/plugins/lists/server/routes/export_exception_list_route.ts b/x-pack/plugins/lists/server/routes/export_exception_list_route.ts index 1394bf48cd2c7..132df176834bb 100644 --- a/x-pack/plugins/lists/server/routes/export_exception_list_route.ts +++ b/x-pack/plugins/lists/server/routes/export_exception_list_route.ts @@ -4,15 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { exportExceptionListQuerySchema } from '../../common/schemas'; import { getExceptionListClient } from './utils'; -export const exportExceptionListRoute = (router: IRouter): void => { +export const exportExceptionListRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/export_list_item_route.ts b/x-pack/plugins/lists/server/routes/export_list_item_route.ts index 98167931c4346..6f5321380aa77 100644 --- a/x-pack/plugins/lists/server/routes/export_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/export_list_item_route.ts @@ -6,15 +6,14 @@ import { Stream } from 'stream'; -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { exportListItemQuerySchema } from '../../common/schemas'; import { getListClient } from '.'; -export const exportListItemRoute = (router: IRouter): void => { +export const exportListItemRoute = (router: ListsPluginRouter): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts index d6a459b3ac961..2b7cb6789b376 100644 --- a/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ENDPOINT_LIST_ID, ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getExceptionListClient } from './utils'; -export const findEndpointListItemRoute = (router: IRouter): void => { +export const findEndpointListItemRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts index 103cba700013f..108dd88adb6b3 100644 --- a/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getExceptionListClient } from './utils'; -export const findExceptionListItemRoute = (router: IRouter): void => { +export const findExceptionListItemRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/find_exception_list_route.ts b/x-pack/plugins/lists/server/routes/find_exception_list_route.ts index 41342261ef681..1a284b27da62e 100644 --- a/x-pack/plugins/lists/server/routes/find_exception_list_route.ts +++ b/x-pack/plugins/lists/server/routes/find_exception_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getExceptionListClient } from './utils'; -export const findExceptionListRoute = (router: IRouter): void => { +export const findExceptionListRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/find_list_item_route.ts b/x-pack/plugins/lists/server/routes/find_list_item_route.ts index 454ea891857c3..4734168d270e6 100644 --- a/x-pack/plugins/lists/server/routes/find_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/find_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -18,7 +17,7 @@ import { decodeCursor } from '../services/utils'; import { getListClient } from './utils'; -export const findListItemRoute = (router: IRouter): void => { +export const findListItemRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/find_list_route.ts b/x-pack/plugins/lists/server/routes/find_list_route.ts index d751214006dcc..fc7a69f6df116 100644 --- a/x-pack/plugins/lists/server/routes/find_list_route.ts +++ b/x-pack/plugins/lists/server/routes/find_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -14,7 +13,7 @@ import { decodeCursor } from '../services/utils'; import { getListClient } from './utils'; -export const findListRoute = (router: IRouter): void => { +export const findListRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/import_list_item_route.ts b/x-pack/plugins/lists/server/routes/import_list_item_route.ts index f7ecc7ac1ac83..0039f7f5d9f90 100644 --- a/x-pack/plugins/lists/server/routes/import_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/import_list_item_route.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +17,7 @@ import { createStreamFromBuffer } from './utils/create_stream_from_buffer'; import { getListClient } from '.'; -export const importListItemRoute = (router: IRouter, config: ConfigType): void => { +export const importListItemRoute = (router: ListsPluginRouter, config: ConfigType): void => { router.post( { options: { diff --git a/x-pack/plugins/lists/server/routes/init_routes.ts b/x-pack/plugins/lists/server/routes/init_routes.ts index 1f29d0aaeeb48..a176bd39bb503 100644 --- a/x-pack/plugins/lists/server/routes/init_routes.ts +++ b/x-pack/plugins/lists/server/routes/init_routes.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ConfigType } from '../config'; import { @@ -46,7 +45,7 @@ import { updateListRoute, } from '.'; -export const initRoutes = (router: IRouter, config: ConfigType): void => { +export const initRoutes = (router: ListsPluginRouter, config: ConfigType): void => { // lists createListRoute(router); readListRoute(router); diff --git a/x-pack/plugins/lists/server/routes/patch_list_item_route.ts b/x-pack/plugins/lists/server/routes/patch_list_item_route.ts index 58cca0313006d..a14d70106cb7b 100644 --- a/x-pack/plugins/lists/server/routes/patch_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/patch_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { listItemSchema, patchListItemSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const patchListItemRoute = (router: IRouter): void => { +export const patchListItemRoute = (router: ListsPluginRouter): void => { router.patch( { options: { diff --git a/x-pack/plugins/lists/server/routes/patch_list_route.ts b/x-pack/plugins/lists/server/routes/patch_list_route.ts index 763f3f495ca17..9c5b59cefb5bc 100644 --- a/x-pack/plugins/lists/server/routes/patch_list_route.ts +++ b/x-pack/plugins/lists/server/routes/patch_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { listSchema, patchListSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const patchListRoute = (router: IRouter): void => { +export const patchListRoute = (router: ListsPluginRouter): void => { router.patch( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts index e80347d97bb7a..2dc79483b4348 100644 --- a/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionListItem, getExceptionListClient } from './utils'; -export const readEndpointListItemRoute = (router: IRouter): void => { +export const readEndpointListItemRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/read_exception_list_item_route.ts index 0cfac6467f089..139a485ab0c5d 100644 --- a/x-pack/plugins/lists/server/routes/read_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/read_exception_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionListItem, getExceptionListClient } from './utils'; -export const readExceptionListItemRoute = (router: IRouter): void => { +export const readExceptionListItemRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_exception_list_route.ts b/x-pack/plugins/lists/server/routes/read_exception_list_route.ts index d9359881616f4..a8dffa696ea7f 100644 --- a/x-pack/plugins/lists/server/routes/read_exception_list_route.ts +++ b/x-pack/plugins/lists/server/routes/read_exception_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionList, getExceptionListClient } from './utils'; -export const readExceptionListRoute = (router: IRouter): void => { +export const readExceptionListRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_list_index_route.ts b/x-pack/plugins/lists/server/routes/read_list_index_route.ts index 5524c1beeaa52..1cb6a63e08cf7 100644 --- a/x-pack/plugins/lists/server/routes/read_list_index_route.ts +++ b/x-pack/plugins/lists/server/routes/read_list_index_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_INDEX } from '../../common/constants'; import { buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { listItemIndexExistSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const readListIndexRoute = (router: IRouter): void => { +export const readListIndexRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_list_item_route.ts b/x-pack/plugins/lists/server/routes/read_list_item_route.ts index 99d34d0fd84a6..677bc49c21a5e 100644 --- a/x-pack/plugins/lists/server/routes/read_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/read_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { listItemArraySchema, listItemSchema, readListItemSchema } from '../../common/schemas'; @@ -13,7 +12,7 @@ import { validate } from '../../common/shared_imports'; import { getListClient } from '.'; -export const readListItemRoute = (router: IRouter): void => { +export const readListItemRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_list_route.ts b/x-pack/plugins/lists/server/routes/read_list_route.ts index da3cf73b56819..1854647460f93 100644 --- a/x-pack/plugins/lists/server/routes/read_list_route.ts +++ b/x-pack/plugins/lists/server/routes/read_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { listSchema, readListSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const readListRoute = (router: IRouter): void => { +export const readListRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/read_privileges_route.ts b/x-pack/plugins/lists/server/routes/read_privileges_route.ts index 4a82f4c5e9cb2..abb43ba43a186 100644 --- a/x-pack/plugins/lists/server/routes/read_privileges_route.ts +++ b/x-pack/plugins/lists/server/routes/read_privileges_route.ts @@ -4,15 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; import { merge } from 'lodash/fp'; +import type { ListsPluginRouter } from '../types'; import { LIST_PRIVILEGES_URL } from '../../common/constants'; import { buildSiemResponse, readPrivileges, transformError } from '../siem_server_deps'; import { getListClient } from './utils'; -export const readPrivilegesRoute = (router: IRouter): void => { +export const readPrivilegesRoute = (router: ListsPluginRouter): void => { router.get( { options: { diff --git a/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts index 8312f2fc87b98..fb2149b3c3d66 100644 --- a/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getExceptionListClient } from '.'; -export const updateEndpointListItemRoute = (router: IRouter): void => { +export const updateEndpointListItemRoute = (router: ListsPluginRouter): void => { router.put( { options: { diff --git a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts index 9ad563724b860..dea53f99810bf 100644 --- a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -18,7 +17,7 @@ import { updateExceptionListItemValidate } from '../../common/schemas/request/up import { getExceptionListClient } from '.'; -export const updateExceptionListItemRoute = (router: IRouter): void => { +export const updateExceptionListItemRoute = (router: ListsPluginRouter): void => { router.put( { options: { diff --git a/x-pack/plugins/lists/server/routes/update_exception_list_route.ts b/x-pack/plugins/lists/server/routes/update_exception_list_route.ts index 47008e3b78fae..c3fa907c706d5 100644 --- a/x-pack/plugins/lists/server/routes/update_exception_list_route.ts +++ b/x-pack/plugins/lists/server/routes/update_exception_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { EXCEPTION_LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -17,7 +16,7 @@ import { import { getErrorMessageExceptionList, getExceptionListClient } from './utils'; -export const updateExceptionListRoute = (router: IRouter): void => { +export const updateExceptionListRoute = (router: ListsPluginRouter): void => { router.put( { options: { diff --git a/x-pack/plugins/lists/server/routes/update_list_item_route.ts b/x-pack/plugins/lists/server/routes/update_list_item_route.ts index 3490027b12747..d7aec97aace67 100644 --- a/x-pack/plugins/lists/server/routes/update_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/update_list_item_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { listItemSchema, updateListItemSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const updateListItemRoute = (router: IRouter): void => { +export const updateListItemRoute = (router: ListsPluginRouter): void => { router.put( { options: { diff --git a/x-pack/plugins/lists/server/routes/update_list_route.ts b/x-pack/plugins/lists/server/routes/update_list_route.ts index 8d7d08be4130b..de8412bc3fddb 100644 --- a/x-pack/plugins/lists/server/routes/update_list_route.ts +++ b/x-pack/plugins/lists/server/routes/update_list_route.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; - +import type { ListsPluginRouter } from '../types'; import { LIST_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/shared_imports'; @@ -13,7 +12,7 @@ import { listSchema, updateListSchema } from '../../common/schemas'; import { getListClient } from '.'; -export const updateListRoute = (router: IRouter): void => { +export const updateListRoute = (router: ListsPluginRouter): void => { router.put( { options: { diff --git a/x-pack/plugins/lists/server/routes/utils/get_exception_list_client.ts b/x-pack/plugins/lists/server/routes/utils/get_exception_list_client.ts index ba01ca617fb8b..b9b7beab65295 100644 --- a/x-pack/plugins/lists/server/routes/utils/get_exception_list_client.ts +++ b/x-pack/plugins/lists/server/routes/utils/get_exception_list_client.ts @@ -4,12 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'kibana/server'; - +import type { ListsRequestHandlerContext } from '../../types'; import { ErrorWithStatusCode } from '../../error_with_status_code'; import { ExceptionListClient } from '../../services/exception_lists/exception_list_client'; -export const getExceptionListClient = (context: RequestHandlerContext): ExceptionListClient => { +export const getExceptionListClient = ( + context: ListsRequestHandlerContext +): ExceptionListClient => { const exceptionLists = context.lists?.getExceptionListClient(); if (exceptionLists == null) { throw new ErrorWithStatusCode('Exception lists is not found as a plugin', 404); diff --git a/x-pack/plugins/lists/server/routes/utils/get_list_client.ts b/x-pack/plugins/lists/server/routes/utils/get_list_client.ts index 6ad69fd994bfd..bc06d753b7b66 100644 --- a/x-pack/plugins/lists/server/routes/utils/get_list_client.ts +++ b/x-pack/plugins/lists/server/routes/utils/get_list_client.ts @@ -4,12 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from 'kibana/server'; - import { ListClient } from '../../services/lists/list_client'; import { ErrorWithStatusCode } from '../../error_with_status_code'; +import type { ListsRequestHandlerContext } from '../../types'; -export const getListClient = (context: RequestHandlerContext): ListClient => { +export const getListClient = (context: ListsRequestHandlerContext): ListClient => { const lists = context.lists?.getListClient(); if (lists == null) { throw new ErrorWithStatusCode('Lists is not found as a plugin', 404); diff --git a/x-pack/plugins/lists/server/types.ts b/x-pack/plugins/lists/server/types.ts index 7d0a24ccddfd0..70cad625245b0 100644 --- a/x-pack/plugins/lists/server/types.ts +++ b/x-pack/plugins/lists/server/types.ts @@ -6,8 +6,9 @@ import { IContextProvider, + IRouter, LegacyAPICaller, - RequestHandler, + RequestHandlerContext, SavedObjectsClientContract, } from 'kibana/server'; @@ -17,7 +18,7 @@ import type { SpacesPluginStart } from '../../spaces/server'; import { ListClient } from './services/lists/list_client'; import { ExceptionListClient } from './services/exception_lists/exception_list_client'; -export type ContextProvider = IContextProvider, 'lists'>; +export type ContextProvider = IContextProvider; export type ListsPluginStart = void; export interface PluginsStart { security: SecurityPluginStart | undefined | null; @@ -40,15 +41,26 @@ export interface ListPluginSetup { getListClient: GetListClientType; } -export type ContextProviderReturn = Promise<{ +/** + * @public + */ +export interface ListsApiRequestHandlerContext { getListClient: () => ListClient; getExceptionListClient: () => ExceptionListClient; -}>; -declare module 'src/core/server' { - interface RequestHandlerContext { - lists?: { - getExceptionListClient: () => ExceptionListClient; - getListClient: () => ListClient; - }; - } } + +/** + * @internal + */ +export interface ListsRequestHandlerContext extends RequestHandlerContext { + lists?: ListsApiRequestHandlerContext; +} + +/** + * @internal + */ +export type ListsPluginRouter = IRouter; +/** + * @internal + */ +export type ContextProviderReturn = Promise; diff --git a/x-pack/plugins/logstash/server/plugin.ts b/x-pack/plugins/logstash/server/plugin.ts index 4a6d476551db0..2c0a714b96910 100644 --- a/x-pack/plugins/logstash/server/plugin.ts +++ b/x-pack/plugins/logstash/server/plugin.ts @@ -16,6 +16,7 @@ import { PluginSetupContract as FeaturesPluginSetup } from '../../features/serve import { SecurityPluginSetup } from '../../security/server'; import { registerRoutes } from './routes'; +import type { LogstashRequestHandlerContext } from './types'; interface SetupDeps { licensing: LicensingPluginSetup; @@ -55,9 +56,12 @@ export class LogstashPlugin implements Plugin { start(core: CoreStart) { const esClient = core.elasticsearch.legacy.createClient('logstash'); - this.coreSetup!.http.registerRouteHandlerContext('logstash', async (context, request) => { - return { esClient: esClient.asScoped(request) }; - }); + this.coreSetup!.http.registerRouteHandlerContext( + 'logstash', + async (context, request) => { + return { esClient: esClient.asScoped(request) }; + } + ); } stop() { if (this.esClient) { diff --git a/x-pack/plugins/logstash/server/routes/cluster/load.ts b/x-pack/plugins/logstash/server/routes/cluster/load.ts index 18fe21f3da675..307e1ebdb55a5 100644 --- a/x-pack/plugins/logstash/server/routes/cluster/load.ts +++ b/x-pack/plugins/logstash/server/routes/cluster/load.ts @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; import { wrapRouteWithLicenseCheck } from '../../../../licensing/server'; import { Cluster } from '../../models/cluster'; import { checkLicense } from '../../lib/check_license'; +import type { LogstashPluginRouter } from '../../types'; -export function registerClusterLoadRoute(router: IRouter) { +export function registerClusterLoadRoute(router: LogstashPluginRouter) { router.get( { path: '/api/logstash/cluster', diff --git a/x-pack/plugins/logstash/server/routes/index.ts b/x-pack/plugins/logstash/server/routes/index.ts index 422afbf7d411e..b62be3a566d4f 100644 --- a/x-pack/plugins/logstash/server/routes/index.ts +++ b/x-pack/plugins/logstash/server/routes/index.ts @@ -3,8 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; import { SecurityPluginSetup } from '../../../security/server'; +import type { LogstashPluginRouter } from '../types'; import { registerClusterLoadRoute } from './cluster'; import { registerPipelineDeleteRoute, @@ -13,7 +13,7 @@ import { } from './pipeline'; import { registerPipelinesListRoute, registerPipelinesDeleteRoute } from './pipelines'; -export function registerRoutes(router: IRouter, security?: SecurityPluginSetup) { +export function registerRoutes(router: LogstashPluginRouter, security?: SecurityPluginSetup) { registerClusterLoadRoute(router); registerPipelineDeleteRoute(router); diff --git a/x-pack/plugins/logstash/server/routes/pipeline/delete.ts b/x-pack/plugins/logstash/server/routes/pipeline/delete.ts index d94b3b94b1df0..e6f335c390ed1 100644 --- a/x-pack/plugins/logstash/server/routes/pipeline/delete.ts +++ b/x-pack/plugins/logstash/server/routes/pipeline/delete.ts @@ -4,12 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; import { wrapRouteWithLicenseCheck } from '../../../../licensing/server'; - +import type { LogstashPluginRouter } from '../../types'; import { checkLicense } from '../../lib/check_license'; -export function registerPipelineDeleteRoute(router: IRouter) { +export function registerPipelineDeleteRoute(router: LogstashPluginRouter) { router.delete( { path: '/api/logstash/pipeline/{id}', diff --git a/x-pack/plugins/logstash/server/routes/pipeline/load.ts b/x-pack/plugins/logstash/server/routes/pipeline/load.ts index 69d16fb82d869..d26e901ca252a 100644 --- a/x-pack/plugins/logstash/server/routes/pipeline/load.ts +++ b/x-pack/plugins/logstash/server/routes/pipeline/load.ts @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { LogstashPluginRouter } from '../../types'; import { Pipeline } from '../../models/pipeline'; import { wrapRouteWithLicenseCheck } from '../../../../licensing/server'; import { checkLicense } from '../../lib/check_license'; -export function registerPipelineLoadRoute(router: IRouter) { +export function registerPipelineLoadRoute(router: LogstashPluginRouter) { router.get( { path: '/api/logstash/pipeline/{id}', diff --git a/x-pack/plugins/logstash/server/routes/pipeline/save.ts b/x-pack/plugins/logstash/server/routes/pipeline/save.ts index e5f28bda1974c..ddeb134ca6046 100644 --- a/x-pack/plugins/logstash/server/routes/pipeline/save.ts +++ b/x-pack/plugins/logstash/server/routes/pipeline/save.ts @@ -5,14 +5,17 @@ */ import { schema } from '@kbn/config-schema'; import { i18n } from '@kbn/i18n'; -import { IRouter } from 'src/core/server'; import { Pipeline } from '../../models/pipeline'; import { wrapRouteWithLicenseCheck } from '../../../../licensing/server'; import { SecurityPluginSetup } from '../../../../security/server'; import { checkLicense } from '../../lib/check_license'; +import type { LogstashPluginRouter } from '../../types'; -export function registerPipelineSaveRoute(router: IRouter, security?: SecurityPluginSetup) { +export function registerPipelineSaveRoute( + router: LogstashPluginRouter, + security?: SecurityPluginSetup +) { router.put( { path: '/api/logstash/pipeline/{id}', diff --git a/x-pack/plugins/logstash/server/routes/pipelines/delete.ts b/x-pack/plugins/logstash/server/routes/pipelines/delete.ts index 4eb3cae1d0956..1dff01f8768b7 100644 --- a/x-pack/plugins/logstash/server/routes/pipelines/delete.ts +++ b/x-pack/plugins/logstash/server/routes/pipelines/delete.ts @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { LegacyAPICaller, IRouter } from 'src/core/server'; +import { LegacyAPICaller } from 'src/core/server'; import { wrapRouteWithLicenseCheck } from '../../../../licensing/server'; import { checkLicense } from '../../lib/check_license'; +import type { LogstashPluginRouter } from '../../types'; async function deletePipelines(callWithRequest: LegacyAPICaller, pipelineIds: string[]) { const deletePromises = pipelineIds.map((pipelineId) => { @@ -29,7 +30,7 @@ async function deletePipelines(callWithRequest: LegacyAPICaller, pipelineIds: st }; } -export function registerPipelinesDeleteRoute(router: IRouter) { +export function registerPipelinesDeleteRoute(router: LogstashPluginRouter) { router.post( { path: '/api/logstash/pipelines/delete', @@ -42,7 +43,7 @@ export function registerPipelinesDeleteRoute(router: IRouter) { wrapRouteWithLicenseCheck( checkLicense, router.handleLegacyErrors(async (context, request, response) => { - const client = context.logstash!.esClient; + const client = context.logstash.esClient; const results = await deletePipelines(client.callAsCurrentUser, request.body.pipelineIds); return response.ok({ body: { results } }); diff --git a/x-pack/plugins/logstash/server/routes/pipelines/list.ts b/x-pack/plugins/logstash/server/routes/pipelines/list.ts index 78690d3091cbd..e6e7c40eecaea 100644 --- a/x-pack/plugins/logstash/server/routes/pipelines/list.ts +++ b/x-pack/plugins/logstash/server/routes/pipelines/list.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; -import { LegacyAPICaller, IRouter } from 'src/core/server'; +import { LegacyAPICaller } from 'src/core/server'; +import type { LogstashPluginRouter } from '../../types'; import { wrapRouteWithLicenseCheck } from '../../../../licensing/server'; import { PipelineListItem } from '../../models/pipeline_list_item'; @@ -20,7 +21,7 @@ async function fetchPipelines(callWithRequest: LegacyAPICaller) { return await callWithRequest('transport.request', params); } -export function registerPipelinesListRoute(router: IRouter) { +export function registerPipelinesListRoute(router: LogstashPluginRouter) { router.get( { path: '/api/logstash/pipelines', diff --git a/x-pack/plugins/logstash/server/types.ts b/x-pack/plugins/logstash/server/types.ts index d9fd109b20943..1fb74d43f1f4f 100644 --- a/x-pack/plugins/logstash/server/types.ts +++ b/x-pack/plugins/logstash/server/types.ts @@ -3,7 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { ILegacyScopedClusterClient } from 'src/core/server'; +import type { ILegacyScopedClusterClient, IRouter, RequestHandlerContext } from 'src/core/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; export interface PipelineListItemOptions { id: string; @@ -12,10 +13,17 @@ export interface PipelineListItemOptions { username: string; } -declare module 'src/core/server' { - interface RequestHandlerContext { - logstash?: { - esClient: ILegacyScopedClusterClient; - }; - } +/** + * @internal + */ +export interface LogstashRequestHandlerContext extends RequestHandlerContext { + logstash: { + esClient: ILegacyScopedClusterClient; + }; + licensing: LicensingApiRequestHandlerContext; } + +/** + * @internal + */ +export type LogstashPluginRouter = IRouter; diff --git a/x-pack/plugins/monitoring/server/plugin.ts b/x-pack/plugins/monitoring/server/plugin.ts index c7b3f13dd6954..a78c50722368d 100644 --- a/x-pack/plugins/monitoring/server/plugin.ts +++ b/x-pack/plugins/monitoring/server/plugin.ts @@ -12,7 +12,6 @@ import { TypeOf } from '@kbn/config-schema'; import { Logger, PluginInitializerContext, - RequestHandlerContext, KibanaRequest, KibanaResponseFactory, CoreSetup, @@ -47,6 +46,7 @@ import { PluginsSetup, PluginsStart, LegacyRequest, + RequestHandlerContextMonitoringPlugin, } from './types'; import { Globals } from './static_globals'; @@ -90,7 +90,7 @@ export class Plugin { .pipe(first()) .toPromise(); - const router = core.http.createRouter(); + const router = core.http.createRouter(); this.legacyShimDependencies = { router, instanceUuid: this.initializerContext.env.instanceUuid, @@ -307,7 +307,7 @@ export class Plugin { route: (options: any) => { const method = options.method; const handler = async ( - context: RequestHandlerContext, + context: RequestHandlerContextMonitoringPlugin, req: KibanaRequest, res: KibanaResponseFactory ) => { diff --git a/x-pack/plugins/monitoring/server/types.ts b/x-pack/plugins/monitoring/server/types.ts index dd6ec9c7930e5..fbdd01e56c657 100644 --- a/x-pack/plugins/monitoring/server/types.ts +++ b/x-pack/plugins/monitoring/server/types.ts @@ -4,10 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ import { Observable } from 'rxjs'; -import { IRouter, ILegacyClusterClient, Logger, ILegacyCustomClusterClient } from 'kibana/server'; +import type { + IRouter, + ILegacyClusterClient, + Logger, + ILegacyCustomClusterClient, + RequestHandlerContext, +} from 'kibana/server'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { LicenseFeature, ILicense } from '../../licensing/server'; -import { PluginStartContract as ActionsPluginsStartContact } from '../../actions/server'; +import type { + PluginStartContract as ActionsPluginsStartContact, + ActionsApiRequestHandlerContext, +} from '../../actions/server'; +import type { AlertingApiRequestHandlerContext } from '../../alerts/server'; import { PluginStartContract as AlertingPluginStartContract, PluginSetupContract as AlertingPluginSetupContract, @@ -42,6 +52,11 @@ export interface PluginsSetup { cloud?: CloudSetup; } +export interface RequestHandlerContextMonitoringPlugin extends RequestHandlerContext { + actions?: ActionsApiRequestHandlerContext; + alerting?: AlertingApiRequestHandlerContext; +} + export interface PluginsStart { alerts: AlertingPluginStartContract; actions: ActionsPluginsStartContact; @@ -53,7 +68,7 @@ export interface MonitoringCoreConfig { export interface RouteDependencies { cluster: ILegacyCustomClusterClient; - router: IRouter; + router: IRouter; licenseService: MonitoringLicenseService; encryptedSavedObjects?: EncryptedSavedObjectsPluginSetup; logger: Logger; @@ -66,7 +81,7 @@ export interface MonitoringCore { } export interface LegacyShimDependencies { - router: IRouter; + router: IRouter; instanceUuid: string; esDataClient: ILegacyClusterClient; kibanaStatsCollector: any; diff --git a/x-pack/plugins/observability/server/lib/annotations/bootstrap_annotations.ts b/x-pack/plugins/observability/server/lib/annotations/bootstrap_annotations.ts index f57e1a774a8e2..6fcd780d5af29 100644 --- a/x-pack/plugins/observability/server/lib/annotations/bootstrap_annotations.ts +++ b/x-pack/plugins/observability/server/lib/annotations/bootstrap_annotations.ts @@ -3,15 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { - CoreSetup, - PluginInitializerContext, - KibanaRequest, - RequestHandlerContext, -} from 'kibana/server'; +import { CoreSetup, PluginInitializerContext, KibanaRequest } from 'kibana/server'; import { PromiseReturnType } from '../../../typings/common'; import { createAnnotationsClient } from './create_annotations_client'; import { registerAnnotationAPIs } from './register_annotation_apis'; +import type { ObservabilityRequestHandlerContext } from '../../types'; interface Params { index: string; @@ -36,7 +32,10 @@ export async function bootstrapAnnotations({ index, core, context }: Params) { }); return { - getScopedAnnotationsClient: (requestContext: RequestHandlerContext, request: KibanaRequest) => { + getScopedAnnotationsClient: ( + requestContext: ObservabilityRequestHandlerContext, + request: KibanaRequest + ) => { return createAnnotationsClient({ index, apiCaller: requestContext.core.elasticsearch.legacy.client.callAsCurrentUser, diff --git a/x-pack/plugins/observability/server/lib/annotations/register_annotation_apis.ts b/x-pack/plugins/observability/server/lib/annotations/register_annotation_apis.ts index 5d0fdc65117bf..8f0b53b5a3df2 100644 --- a/x-pack/plugins/observability/server/lib/annotations/register_annotation_apis.ts +++ b/x-pack/plugins/observability/server/lib/annotations/register_annotation_apis.ts @@ -15,6 +15,7 @@ import { } from '../../../common/annotations'; import { ScopedAnnotationsClient } from './bootstrap_annotations'; import { createAnnotationsClient } from './create_annotations_client'; +import type { ObservabilityRequestHandlerContext } from '../../types'; const unknowns = schema.object({}, { unknowns: 'allow' }); @@ -30,8 +31,12 @@ export function registerAnnotationAPIs({ function wrapRouteHandler>( types: TType, handler: (params: { data: t.TypeOf; client: ScopedAnnotationsClient }) => Promise - ): RequestHandler { - return async (...args: Parameters) => { + ): RequestHandler { + return async ( + ...args: Parameters< + RequestHandler + > + ) => { const [context, request, response] = args; const rt = types; @@ -79,7 +84,7 @@ export function registerAnnotationAPIs({ }; } - const router = core.http.createRouter(); + const router = core.http.createRouter(); router.post( { diff --git a/x-pack/plugins/observability/server/types.ts b/x-pack/plugins/observability/server/types.ts new file mode 100644 index 0000000000000..ee4761a94dcc5 --- /dev/null +++ b/x-pack/plugins/observability/server/types.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 type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; + +/** + * @internal + */ +export interface ObservabilityRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; +} + +/** + * @internal + */ +export type ObservabilityPluginRouter = IRouter; diff --git a/x-pack/plugins/reporting/server/core.ts b/x-pack/plugins/reporting/server/core.ts index 2c1ac95d6e824..b227b3ba5d0d5 100644 --- a/x-pack/plugins/reporting/server/core.ts +++ b/x-pack/plugins/reporting/server/core.ts @@ -10,7 +10,6 @@ import { first, map, take } from 'rxjs/operators'; import { BasePath, ElasticsearchServiceSetup, - IRouter, KibanaRequest, SavedObjectsClientContract, SavedObjectsServiceStart, @@ -27,10 +26,11 @@ import { checkLicense, getExportTypesRegistry, LevelLogger } from './lib'; import { ESQueueInstance } from './lib/create_queue'; import { screenshotsObservableFactory, ScreenshotsObservableFn } from './lib/screenshots'; import { ReportingStore } from './lib/store'; +import { ReportingPluginRouter } from './types'; export interface ReportingInternalSetup { basePath: Pick; - router: IRouter; + router: ReportingPluginRouter; features: FeaturesPluginSetup; elasticsearch: ElasticsearchServiceSetup; licensing: LicensingPluginSetup; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts index 96653b1573662..24516210efc54 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts @@ -6,7 +6,6 @@ import { notFound, notImplemented } from '@hapi/boom'; import { get } from 'lodash'; -import { RequestHandlerContext } from 'src/core/server'; import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants'; import { CsvFromSavedObjectRequest } from '../../routes/generate_from_savedobject_immediate'; import { CreateJobFnFactory } from '../../types'; @@ -18,10 +17,11 @@ import { SavedObjectServiceError, VisObjectAttributesJSON, } from './types'; +import type { ReportingRequestHandlerContext } from '../../types'; export type ImmediateCreateJobFn = ( jobParams: JobParamsPanelCsv, - context: RequestHandlerContext, + context: ReportingRequestHandlerContext, req: CsvFromSavedObjectRequest ) => Promise; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts index 5e95eec99871f..f8df8c8f16a65 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; import { CancellationToken } from '../../../common'; import { CONTENT_TYPE_CSV, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants'; import { TaskRunResult } from '../../lib/tasks'; @@ -12,6 +12,7 @@ import { RunTaskFnFactory } from '../../types'; import { createGenerateCsv } from '../csv/generate_csv'; import { getGenerateCsvParams } from './lib/get_csv_job'; import { JobPayloadPanelCsv } from './types'; +import type { ReportingRequestHandlerContext } from '../../types'; /* * ImmediateExecuteFn receives the job doc payload because the payload was @@ -20,7 +21,7 @@ import { JobPayloadPanelCsv } from './types'; export type ImmediateExecuteFn = ( jobId: null, job: JobPayloadPanelCsv, - context: RequestHandlerContext, + context: ReportingRequestHandlerContext, req: KibanaRequest ) => Promise; diff --git a/x-pack/plugins/reporting/server/lib/enqueue_job.ts b/x-pack/plugins/reporting/server/lib/enqueue_job.ts index 305247e6f8637..daa662478d82b 100644 --- a/x-pack/plugins/reporting/server/lib/enqueue_job.ts +++ b/x-pack/plugins/reporting/server/lib/enqueue_job.ts @@ -4,18 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; import { ReportingCore } from '../'; import { durationToNumber } from '../../common/schema_utils'; import { BaseParams, ReportingUser } from '../types'; import { LevelLogger } from './'; import { Report } from './store'; +import type { ReportingRequestHandlerContext } from '../types'; export type EnqueueJobFn = ( exportTypeId: string, jobParams: BaseParams, user: ReportingUser, - context: RequestHandlerContext, + context: ReportingRequestHandlerContext, request: KibanaRequest ) => Promise; @@ -36,7 +37,7 @@ export function enqueueJobFactory( exportTypeId: string, jobParams: BaseParams, user: ReportingUser, - context: RequestHandlerContext, + context: ReportingRequestHandlerContext, request: KibanaRequest ) { const exportType = reporting.getExportTypesRegistry().getById(exportTypeId); diff --git a/x-pack/plugins/reporting/server/plugin.ts b/x-pack/plugins/reporting/server/plugin.ts index 6a93a35bfcc84..05556f050e213 100644 --- a/x-pack/plugins/reporting/server/plugin.ts +++ b/x-pack/plugins/reporting/server/plugin.ts @@ -16,15 +16,10 @@ import { registerRoutes } from './routes'; import { setFieldFormats } from './services'; import { ReportingSetup, ReportingSetupDeps, ReportingStart, ReportingStartDeps } from './types'; import { registerReportingUsageCollector } from './usage'; +import type { ReportingRequestHandlerContext } from './types'; const kbToBase64Length = (kb: number) => Math.floor((kb * 1024 * 8) / 6); -declare module 'src/core/server' { - interface RequestHandlerContext { - reporting?: ReportingStart | null; - } -} - export class ReportingPlugin implements Plugin { private readonly initializerContext: PluginInitializerContext; @@ -39,6 +34,7 @@ export class ReportingPlugin public setup(core: CoreSetup, plugins: ReportingSetupDeps) { // prevent throwing errors in route handlers about async deps not being initialized + // @ts-expect-error null is not assignable to object. use a boolean property to ensure reporting API is enabled. core.http.registerRouteHandlerContext(PLUGIN_ID, () => { if (this.reportingCore.pluginIsStarted()) { return {}; // ReportingStart contract @@ -73,7 +69,7 @@ export class ReportingPlugin const { features, licensing, security, spaces } = plugins; const { initializerContext: initContext, reportingCore } = this; - const router = http.createRouter(); + const router = http.createRouter(); const basePath = http.basePath; reportingCore.pluginSetup({ diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/browser.test.ts b/x-pack/plugins/reporting/server/routes/diagnostic/browser.test.ts index 71ca0661a42a9..65519dab9a975 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/browser.test.ts +++ b/x-pack/plugins/reporting/server/routes/diagnostic/browser.test.ts @@ -12,6 +12,7 @@ import supertest from 'supertest'; import { ReportingCore } from '../..'; import { createMockLevelLogger, createMockReportingCore } from '../../test_helpers'; import { registerDiagnoseBrowser } from './browser'; +import type { ReportingRequestHandlerContext } from '../../types'; jest.mock('child_process'); jest.mock('readline'); @@ -47,7 +48,11 @@ describe('POST /diagnose/browser', () => { beforeEach(async () => { ({ server, httpSetup } = await setupServer(reportingSymbol)); - httpSetup.registerRouteHandlerContext(reportingSymbol, 'reporting', () => ({})); + httpSetup.registerRouteHandlerContext( + reportingSymbol, + 'reporting', + () => ({}) + ); const mockSetupDeps = ({ elasticsearch: { diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/config.test.ts b/x-pack/plugins/reporting/server/routes/diagnostic/config.test.ts index a112d04f38c7b..ef84ee068e8a3 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/config.test.ts +++ b/x-pack/plugins/reporting/server/routes/diagnostic/config.test.ts @@ -10,6 +10,7 @@ import supertest from 'supertest'; import { ReportingCore } from '../..'; import { createMockReportingCore, createMockLevelLogger } from '../../test_helpers'; import { registerDiagnoseConfig } from './config'; +import type { ReportingRequestHandlerContext } from '../../types'; type SetupServerReturn = UnwrapPromise>; @@ -25,7 +26,11 @@ describe('POST /diagnose/config', () => { beforeEach(async () => { ({ server, httpSetup } = await setupServer(reportingSymbol)); - httpSetup.registerRouteHandlerContext(reportingSymbol, 'reporting', () => ({})); + httpSetup.registerRouteHandlerContext( + reportingSymbol, + 'reporting', + () => ({}) + ); mockSetupDeps = ({ elasticsearch: { diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts b/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts index 287da0d2ed5ec..37a8412e4269c 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts +++ b/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts @@ -10,6 +10,7 @@ import supertest from 'supertest'; import { ReportingCore } from '../..'; import { createMockReportingCore, createMockLevelLogger } from '../../test_helpers'; import { registerDiagnoseScreenshot } from './screenshot'; +import type { ReportingRequestHandlerContext } from '../../types'; jest.mock('../../export_types/png/lib/generate_png'); @@ -44,7 +45,11 @@ describe('POST /diagnose/screenshot', () => { beforeEach(async () => { ({ server, httpSetup } = await setupServer(reportingSymbol)); - httpSetup.registerRouteHandlerContext(reportingSymbol, 'reporting', () => ({})); + httpSetup.registerRouteHandlerContext( + reportingSymbol, + 'reporting', + () => ({}) + ); const mockSetupDeps = ({ elasticsearch: { diff --git a/x-pack/plugins/reporting/server/routes/generation.test.ts b/x-pack/plugins/reporting/server/routes/generation.test.ts index 867af75c8de27..b904ff92be3ec 100644 --- a/x-pack/plugins/reporting/server/routes/generation.test.ts +++ b/x-pack/plugins/reporting/server/routes/generation.test.ts @@ -13,6 +13,7 @@ import { ReportingCore } from '..'; import { ExportTypesRegistry } from '../lib/export_types_registry'; import { createMockReportingCore, createMockLevelLogger } from '../test_helpers'; import { registerJobGenerationRoutes } from './generation'; +import type { ReportingRequestHandlerContext } from '../types'; type SetupServerReturn = UnwrapPromise>; @@ -46,7 +47,11 @@ describe('POST /api/reporting/generate', () => { beforeEach(async () => { ({ server, httpSetup } = await setupServer(reportingSymbol)); - httpSetup.registerRouteHandlerContext(reportingSymbol, 'reporting', () => ({})); + httpSetup.registerRouteHandlerContext( + reportingSymbol, + 'reporting', + () => ({}) + ); callClusterStub = sinon.stub().resolves({}); diff --git a/x-pack/plugins/reporting/server/routes/jobs.test.ts b/x-pack/plugins/reporting/server/routes/jobs.test.ts index fc1cfd00493c3..ccbec158cb5a1 100644 --- a/x-pack/plugins/reporting/server/routes/jobs.test.ts +++ b/x-pack/plugins/reporting/server/routes/jobs.test.ts @@ -12,7 +12,7 @@ import { ReportingCore } from '..'; import { ReportingInternalSetup } from '../core'; import { ExportTypesRegistry } from '../lib/export_types_registry'; import { createMockConfig, createMockConfigSchema, createMockReportingCore } from '../test_helpers'; -import { ExportTypeDefinition } from '../types'; +import { ExportTypeDefinition, ReportingRequestHandlerContext } from '../types'; import { registerJobInfoRoutes } from './jobs'; type SetupServerReturn = UnwrapPromise>; @@ -35,7 +35,11 @@ describe('GET /api/reporting/jobs/download', () => { beforeEach(async () => { ({ server, httpSetup } = await setupServer(reportingSymbol)); - httpSetup.registerRouteHandlerContext(reportingSymbol, 'reporting', () => ({})); + httpSetup.registerRouteHandlerContext( + reportingSymbol, + 'reporting', + () => ({}) + ); core = await createMockReportingCore(config, ({ elasticsearch: { legacy: { client: { callAsInternalUser: jest.fn() } }, diff --git a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.ts b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.ts index cce002a0e6935..18191a9f1b718 100644 --- a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.ts +++ b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, KibanaResponseFactory, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest, KibanaResponseFactory } from 'kibana/server'; import { coreMock, httpServerMock } from 'src/core/server/mocks'; import { ReportingCore } from '../../'; import { ReportingInternalSetup } from '../../core'; @@ -14,6 +14,7 @@ import { createMockReportingCore, } from '../../test_helpers'; import { authorizedUserPreRoutingFactory } from './authorized_user_pre_routing'; +import type { ReportingRequestHandlerContext } from '../../types'; let mockCore: ReportingCore; const mockConfig: any = { 'server.basePath': '/sbp', 'roles.allow': ['reporting_user'] }; @@ -23,7 +24,7 @@ const mockReportingConfig = createMockConfig(mockReportingConfigSchema); const getMockContext = () => (({ core: coreMock.createRequestHandlerContext(), - } as unknown) as RequestHandlerContext); + } as unknown) as ReportingRequestHandlerContext); const getMockRequest = () => ({ diff --git a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts index 4d57bc154444e..e8be2b1c92882 100644 --- a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts +++ b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts @@ -8,11 +8,17 @@ import { RequestHandler, RouteMethod } from 'src/core/server'; import { AuthenticatedUser } from '../../../../security/server'; import { ReportingCore } from '../../core'; import { getUserFactory } from './get_user'; +import type { ReportingRequestHandlerContext } from '../../types'; const superuserRole = 'superuser'; type ReportingRequestUser = AuthenticatedUser | false; -export type RequestHandlerUser = RequestHandler extends (...a: infer U) => infer R +export type RequestHandlerUser = RequestHandler< + P, + Q, + B, + ReportingRequestHandlerContext +> extends (...a: infer U) => infer R ? (user: ReportingRequestUser, ...a: U) => R : never; @@ -21,7 +27,9 @@ export const authorizedUserPreRoutingFactory = function authorizedUserPreRouting ) { const setupDeps = reporting.getPluginSetupDeps(); const getUser = getUserFactory(setupDeps.security); - return (handler: RequestHandlerUser): RequestHandler => { + return ( + handler: RequestHandlerUser + ): RequestHandler => { return (context, req, res) => { let user: ReportingRequestUser = false; if (setupDeps.security && setupDeps.security.license.isEnabled()) { diff --git a/x-pack/plugins/reporting/server/routes/types.d.ts b/x-pack/plugins/reporting/server/routes/types.d.ts index b3f9225c3dce5..de451773437fc 100644 --- a/x-pack/plugins/reporting/server/routes/types.d.ts +++ b/x-pack/plugins/reporting/server/routes/types.d.ts @@ -4,14 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, KibanaResponseFactory, RequestHandlerContext } from 'src/core/server'; -import { BaseParams, BasePayload, ReportingUser } from '../types'; +import { KibanaRequest, KibanaResponseFactory } from 'src/core/server'; +import type { + BaseParams, + BasePayload, + ReportingUser, + ReportingRequestHandlerContext, +} from '../types'; export type HandlerFunction = ( user: ReportingUser, exportType: string, jobParams: BaseParams, - context: RequestHandlerContext, + context: ReportingRequestHandlerContext, req: KibanaRequest, res: KibanaResponseFactory ) => any; diff --git a/x-pack/plugins/reporting/server/types.ts b/x-pack/plugins/reporting/server/types.ts index 8cd26df032f64..8ad458ed65d4e 100644 --- a/x-pack/plugins/reporting/server/types.ts +++ b/x-pack/plugins/reporting/server/types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import type { IRouter, KibanaRequest, RequestHandlerContext } from 'src/core/server'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { DataPluginStart } from 'src/plugins/data/server/plugin'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; @@ -58,7 +58,7 @@ export interface BasePayload extends BaseParams { // default fn type for CreateJobFnFactory export type CreateJobFn = ( jobParams: JobParamsType, - context: RequestHandlerContext, + context: ReportingRequestHandlerContext, request: KibanaRequest ) => Promise; @@ -89,3 +89,15 @@ export interface ExportTypeDefinition; validLicenses: string[]; } + +/** + * @internal + */ +export interface ReportingRequestHandlerContext extends RequestHandlerContext { + reporting: ReportingStart | null; +} + +/** + * @internal + */ +export type ReportingPluginRouter = IRouter; diff --git a/x-pack/plugins/rollup/server/plugin.ts b/x-pack/plugins/rollup/server/plugin.ts index 3c670f56c7d8f..dc505d1aa5850 100644 --- a/x-pack/plugins/rollup/server/plugin.ts +++ b/x-pack/plugins/rollup/server/plugin.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -declare module 'src/core/server' { - interface RequestHandlerContext { - rollup?: RollupContext; - } -} - import { Observable } from 'rxjs'; import { first } from 'rxjs/operators'; import { @@ -18,14 +12,13 @@ import { Plugin, Logger, PluginInitializerContext, - ILegacyScopedClusterClient, SharedGlobalConfig, } from 'src/core/server'; import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; import { PLUGIN, CONFIG_ROLLUPS } from '../common'; -import { Dependencies } from './types'; +import { Dependencies, RollupHandlerContext } from './types'; import { registerApiRoutes } from './routes'; import { License } from './services'; import { registerRollupUsageCollector } from './collectors'; @@ -36,9 +29,6 @@ import { isEsError } from './shared_imports'; import { formatEsError } from './lib/format_es_error'; import { getCapabilitiesForRollupIndices } from '../../../../src/plugins/data/server'; -interface RollupContext { - client: ILegacyScopedClusterClient; -} async function getCustomEsClient(getStartServices: CoreSetup['getStartServices']) { const [core] = await getStartServices(); // Extend the elasticsearchJs client with additional endpoints. @@ -91,12 +81,15 @@ export class RollupPlugin implements Plugin { ], }); - http.registerRouteHandlerContext('rollup', async (context, request) => { - this.rollupEsClient = this.rollupEsClient ?? (await getCustomEsClient(getStartServices)); - return { - client: this.rollupEsClient.asScoped(request), - }; - }); + http.registerRouteHandlerContext( + 'rollup', + async (context, request) => { + this.rollupEsClient = this.rollupEsClient ?? (await getCustomEsClient(getStartServices)); + return { + client: this.rollupEsClient.asScoped(request), + }; + } + ); registerApiRoutes({ router: http.createRouter(), diff --git a/x-pack/plugins/rollup/server/routes/api/search/register_search_route.ts b/x-pack/plugins/rollup/server/routes/api/search/register_search_route.ts index c5c56336def1a..cdc4c255a5aba 100644 --- a/x-pack/plugins/rollup/server/routes/api/search/register_search_route.ts +++ b/x-pack/plugins/rollup/server/routes/api/search/register_search_route.ts @@ -28,7 +28,7 @@ export const registerSearchRoute = ({ license.guardApiRoute(async (context, request, response) => { try { const requests = request.body.map(({ index, query }: { index: string; query?: any }) => - context.rollup!.client.callAsCurrentUser('rollup.search', { + context.rollup.client.callAsCurrentUser('rollup.search', { index, rest_total_hits_as_int: true, body: query, diff --git a/x-pack/plugins/rollup/server/services/license.ts b/x-pack/plugins/rollup/server/services/license.ts index 5424092a01ee5..f80f91b8d03ee 100644 --- a/x-pack/plugins/rollup/server/services/license.ts +++ b/x-pack/plugins/rollup/server/services/license.ts @@ -4,15 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import { Logger } from 'src/core/server'; -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from 'src/core/server'; +import { KibanaRequest, KibanaResponseFactory, RequestHandler } from 'src/core/server'; import { LicensingPluginSetup } from '../../../licensing/server'; import { LicenseType } from '../../../licensing/common/types'; +import type { RollupHandlerContext } from '../types'; export interface LicenseStatus { isValid: boolean; @@ -59,11 +55,11 @@ export class License { }); } - guardApiRoute(handler: RequestHandler) { + guardApiRoute(handler: RequestHandler) { const license = this; return function licenseCheck( - ctx: RequestHandlerContext, + ctx: RollupHandlerContext, request: KibanaRequest, response: KibanaResponseFactory ) { diff --git a/x-pack/plugins/rollup/server/types.ts b/x-pack/plugins/rollup/server/types.ts index 89e13e69c4da2..e6fe0eae15edd 100644 --- a/x-pack/plugins/rollup/server/types.ts +++ b/x-pack/plugins/rollup/server/types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import { IRouter, ILegacyScopedClusterClient, RequestHandlerContext } from 'src/core/server'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { VisTypeTimeseriesSetup } from 'src/plugins/vis_type_timeseries/server'; @@ -26,7 +26,7 @@ export interface Dependencies { } export interface RouteDependencies { - router: IRouter; + router: RollupPluginRouter; license: License; lib: { isEsError: typeof isEsError; @@ -37,3 +37,22 @@ export interface RouteDependencies { IndexPatternsFetcher: typeof IndexPatternsFetcher; }; } + +/** + * @internal + */ +interface RollupApiRequestHandlerContext { + client: ILegacyScopedClusterClient; +} + +/** + * @internal + */ +export interface RollupHandlerContext extends RequestHandlerContext { + rollup: RollupApiRequestHandlerContext; +} + +/** + * @internal + */ +export type RollupPluginRouter = IRouter; diff --git a/x-pack/plugins/saved_objects_tagging/server/plugin.ts b/x-pack/plugins/saved_objects_tagging/server/plugin.ts index ce687866711e4..4f291b7c033a2 100644 --- a/x-pack/plugins/saved_objects_tagging/server/plugin.ts +++ b/x-pack/plugins/saved_objects_tagging/server/plugin.ts @@ -17,7 +17,7 @@ import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/s import { SecurityPluginSetup } from '../../security/server'; import { savedObjectsTaggingFeature } from './features'; import { tagType } from './saved_objects'; -import { ITagsRequestHandlerContext } from './types'; +import type { TagsHandlerContext } from './types'; import { TagsRequestHandlerContext } from './request_handler_context'; import { registerRoutes } from './routes'; import { createTagUsageCollector } from './usage'; @@ -41,12 +41,12 @@ export class SavedObjectTaggingPlugin implements Plugin<{}, {}, SetupDeps, {}> { ) { savedObjects.registerType(tagType); - const router = http.createRouter(); + const router = http.createRouter(); registerRoutes({ router }); - http.registerRouteHandlerContext( + http.registerRouteHandlerContext( 'tags', - async (context, req, res): Promise => { + async (context, req, res) => { return new TagsRequestHandlerContext(req, context.core, security); } ); diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/assignments/find_assignable_objects.ts b/x-pack/plugins/saved_objects_tagging/server/routes/assignments/find_assignable_objects.ts index dcfb2f801eba9..86fa6d8a7c407 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/assignments/find_assignable_objects.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/assignments/find_assignable_objects.ts @@ -5,10 +5,10 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; import { FindAssignableObjectResponse } from '../../../common/http_api_types'; +import type { TagsPluginRouter } from '../../types'; -export const registerFindAssignableObjectsRoute = (router: IRouter) => { +export const registerFindAssignableObjectsRoute = (router: TagsPluginRouter) => { router.get( { path: '/internal/saved_objects_tagging/assignments/_find_assignable_objects', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/assignments/get_assignable_types.ts b/x-pack/plugins/saved_objects_tagging/server/routes/assignments/get_assignable_types.ts index 182aa6d5ce43d..627244badbcee 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/assignments/get_assignable_types.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/assignments/get_assignable_types.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; import { GetAssignableTypesResponse } from '../../../common/http_api_types'; -export const registerGetAssignableTypesRoute = (router: IRouter) => { +export const registerGetAssignableTypesRoute = (router: TagsPluginRouter) => { router.get( { path: '/internal/saved_objects_tagging/assignments/_assignable_types', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/assignments/update_tags_assignments.ts b/x-pack/plugins/saved_objects_tagging/server/routes/assignments/update_tags_assignments.ts index 2144b7ffd99a9..b2179cd9b092a 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/assignments/update_tags_assignments.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/assignments/update_tags_assignments.ts @@ -5,10 +5,10 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; import { AssignmentError } from '../../services'; -export const registerUpdateTagsAssignmentsRoute = (router: IRouter) => { +export const registerUpdateTagsAssignmentsRoute = (router: TagsPluginRouter) => { const objectReferenceSchema = schema.object({ type: schema.string(), id: schema.string(), diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/index.ts b/x-pack/plugins/saved_objects_tagging/server/routes/index.ts index bba2673b1ce0a..d1204ca96518a 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/index.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/index.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; import { registerUpdateTagRoute, registerGetAllTagsRoute, @@ -18,8 +17,9 @@ import { registerGetAssignableTypesRoute, } from './assignments'; import { registerInternalFindTagsRoute, registerInternalBulkDeleteRoute } from './internal'; +import { TagsPluginRouter } from '../types'; -export const registerRoutes = ({ router }: { router: IRouter }) => { +export const registerRoutes = ({ router }: { router: TagsPluginRouter }) => { // tags API registerCreateTagRoute(router); registerUpdateTagRoute(router); diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts b/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts index bade81678543d..68848f9716a2f 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts @@ -5,9 +5,9 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; -export const registerInternalBulkDeleteRoute = (router: IRouter) => { +export const registerInternalBulkDeleteRoute = (router: TagsPluginRouter) => { router.post( { path: '/internal/saved_objects_tagging/tags/_bulk_delete', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/internal/find_tags.ts b/x-pack/plugins/saved_objects_tagging/server/routes/internal/find_tags.ts index 6e095eb6e4a6e..e99d9c1da7b91 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/internal/find_tags.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/internal/find_tags.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; import { tagSavedObjectTypeName } from '../../../common/constants'; import { TagAttributes } from '../../../common/types'; import { savedObjectToTag } from '../../services/tags'; import { addConnectionCount } from '../lib'; -export const registerInternalFindTagsRoute = (router: IRouter) => { +export const registerInternalFindTagsRoute = (router: TagsPluginRouter) => { router.get( { path: '/internal/saved_objects_tagging/tags/_find', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/tags/create_tag.ts b/x-pack/plugins/saved_objects_tagging/server/routes/tags/create_tag.ts index 499f73c3e0470..56b05a83a333b 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/tags/create_tag.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/tags/create_tag.ts @@ -5,10 +5,10 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; import { TagValidationError } from '../../services/tags'; -export const registerCreateTagRoute = (router: IRouter) => { +export const registerCreateTagRoute = (router: TagsPluginRouter) => { router.post( { path: '/api/saved_objects_tagging/tags/create', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/tags/delete_tag.ts b/x-pack/plugins/saved_objects_tagging/server/routes/tags/delete_tag.ts index 84f798063555e..656a97aece889 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/tags/delete_tag.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/tags/delete_tag.ts @@ -5,9 +5,9 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; -export const registerDeleteTagRoute = (router: IRouter) => { +export const registerDeleteTagRoute = (router: TagsPluginRouter) => { router.delete( { path: '/api/saved_objects_tagging/tags/{id}', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_all_tags.ts b/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_all_tags.ts index cbc43d66f0ecc..3603265beae51 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_all_tags.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_all_tags.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; -export const registerGetAllTagsRoute = (router: IRouter) => { +export const registerGetAllTagsRoute = (router: TagsPluginRouter) => { router.get( { path: '/api/saved_objects_tagging/tags', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_tag.ts b/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_tag.ts index 559c5ed2d8dd1..9f7401d6c1cd7 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_tag.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/tags/get_tag.ts @@ -5,9 +5,9 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; +import type { TagsPluginRouter } from '../../types'; -export const registerGetTagRoute = (router: IRouter) => { +export const registerGetTagRoute = (router: TagsPluginRouter) => { router.get( { path: '/api/saved_objects_tagging/tags/{id}', diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/tags/update_tag.ts b/x-pack/plugins/saved_objects_tagging/server/routes/tags/update_tag.ts index fe8a48ae6e855..b81bc54c1b5dc 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/tags/update_tag.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/tags/update_tag.ts @@ -5,10 +5,10 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter } from 'src/core/server'; import { TagValidationError } from '../../services/tags'; +import type { TagsPluginRouter } from '../../types'; -export const registerUpdateTagRoute = (router: IRouter) => { +export const registerUpdateTagRoute = (router: TagsPluginRouter) => { router.post( { path: '/api/saved_objects_tagging/tags/{id}', diff --git a/x-pack/plugins/saved_objects_tagging/server/types.ts b/x-pack/plugins/saved_objects_tagging/server/types.ts index de5997b84a75c..6e3e151ad8adf 100644 --- a/x-pack/plugins/saved_objects_tagging/server/types.ts +++ b/x-pack/plugins/saved_objects_tagging/server/types.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import type { IRouter, RequestHandlerContext } from 'src/core/server'; import { ITagsClient } from '../common/types'; import { IAssignmentService } from './services'; @@ -12,8 +13,14 @@ export interface ITagsRequestHandlerContext { assignmentService: IAssignmentService; } -declare module 'src/core/server' { - interface RequestHandlerContext { - tags?: ITagsRequestHandlerContext; - } +/** + * @internal + */ +export interface TagsHandlerContext extends RequestHandlerContext { + tags: ITagsRequestHandlerContext; } + +/** + * @internal + */ +export type TagsPluginRouter = IRouter; diff --git a/x-pack/plugins/security/server/routes/api_keys/enabled.test.ts b/x-pack/plugins/security/server/routes/api_keys/enabled.test.ts index 53950cb431941..f329d7a3980cc 100644 --- a/x-pack/plugins/security/server/routes/api_keys/enabled.test.ts +++ b/x-pack/plugins/security/server/routes/api_keys/enabled.test.ts @@ -6,11 +6,7 @@ import Boom from '@hapi/boom'; import type { DeeplyMockedKeys } from '@kbn/utility-types/jest'; -import { - kibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from '../../../../../../src/core/server'; +import { kibanaResponseFactory, RequestHandler } from '../../../../../../src/core/server'; import { httpServerMock } from '../../../../../../src/core/server/mocks'; import { routeDefinitionParamsMock } from '../index.mock'; @@ -18,6 +14,7 @@ import { routeDefinitionParamsMock } from '../index.mock'; import type { AuthenticationServiceStart } from '../../authentication'; import { defineEnabledApiKeysRoutes } from './enabled'; import { authenticationServiceMock } from '../../authentication/authentication_service.mock'; +import type { SecurityRequestHandlerContext } from '../../types'; describe('API keys enabled', () => { function getMockContext( @@ -25,7 +22,7 @@ describe('API keys enabled', () => { ) { return ({ licensing: { license: { check: jest.fn().mockReturnValue(licenseCheckResult) } }, - } as unknown) as RequestHandlerContext; + } as unknown) as SecurityRequestHandlerContext; } let routeHandler: RequestHandler; diff --git a/x-pack/plugins/security/server/routes/authentication/common.test.ts b/x-pack/plugins/security/server/routes/authentication/common.test.ts index b032930e4400a..4073ef9f21c60 100644 --- a/x-pack/plugins/security/server/routes/authentication/common.test.ts +++ b/x-pack/plugins/security/server/routes/authentication/common.test.ts @@ -7,10 +7,8 @@ import { Type } from '@kbn/config-schema'; import type { DeeplyMockedKeys } from '@kbn/utility-types/jest'; import { - IRouter, kibanaResponseFactory, RequestHandler, - RequestHandlerContext, RouteConfig, } from '../../../../../../src/core/server'; import type { SecurityLicense, SecurityLicenseFeatures } from '../../../common/licensing'; @@ -22,6 +20,7 @@ import { SAMLLogin, } from '../../authentication'; import { defineCommonRoutes } from './common'; +import type { SecurityRequestHandlerContext, SecurityRouter } from '../../types'; import { httpServerMock } from '../../../../../../src/core/server/mocks'; import { mockAuthenticatedUser } from '../../../common/model/authenticated_user.mock'; @@ -29,10 +28,10 @@ import { routeDefinitionParamsMock } from '../index.mock'; import { authenticationServiceMock } from '../../authentication/authentication_service.mock'; describe('Common authentication routes', () => { - let router: jest.Mocked; + let router: jest.Mocked; let authc: DeeplyMockedKeys; let license: jest.Mocked; - let mockContext: RequestHandlerContext; + let mockContext: SecurityRequestHandlerContext; beforeEach(() => { const routeParamsMock = routeDefinitionParamsMock.create(); router = routeParamsMock.router; @@ -44,13 +43,13 @@ describe('Common authentication routes', () => { licensing: { license: { check: jest.fn().mockReturnValue({ check: 'valid' }) }, }, - } as unknown) as RequestHandlerContext; + } as unknown) as SecurityRequestHandlerContext; defineCommonRoutes(routeParamsMock); }); describe('logout', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; const mockRequest = httpServerMock.createKibanaRequest({ @@ -151,7 +150,7 @@ describe('Common authentication routes', () => { }); describe('me', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; const mockRequest = httpServerMock.createKibanaRequest({ @@ -185,7 +184,7 @@ describe('Common authentication routes', () => { }); describe('login', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [acsRouteConfig, acsRouteHandler] = router.post.mock.calls.find( @@ -645,7 +644,7 @@ describe('Common authentication routes', () => { }); describe('acknowledge access agreement', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [acsRouteConfig, acsRouteHandler] = router.post.mock.calls.find( diff --git a/x-pack/plugins/security/server/routes/authentication/saml.test.ts b/x-pack/plugins/security/server/routes/authentication/saml.test.ts index d1d5f601d7a43..ad7d141cad681 100644 --- a/x-pack/plugins/security/server/routes/authentication/saml.test.ts +++ b/x-pack/plugins/security/server/routes/authentication/saml.test.ts @@ -8,7 +8,8 @@ import { Type } from '@kbn/config-schema'; import type { DeeplyMockedKeys } from '@kbn/utility-types/jest'; import { AuthenticationResult, AuthenticationServiceStart, SAMLLogin } from '../../authentication'; import { defineSAMLRoutes } from './saml'; -import type { IRouter, RequestHandler, RouteConfig } from '../../../../../../src/core/server'; +import type { RequestHandler, RouteConfig } from '../../../../../../src/core/server'; +import type { SecurityRouter } from '../../types'; import { httpServerMock } from '../../../../../../src/core/server/mocks'; import { mockAuthenticatedUser } from '../../../common/model/authenticated_user.mock'; @@ -16,7 +17,7 @@ import { routeDefinitionParamsMock } from '../index.mock'; import { authenticationServiceMock } from '../../authentication/authentication_service.mock'; describe('SAML authentication routes', () => { - let router: jest.Mocked; + let router: jest.Mocked; let authc: DeeplyMockedKeys; beforeEach(() => { const routeParamsMock = routeDefinitionParamsMock.create(); diff --git a/x-pack/plugins/security/server/routes/authorization/privileges/get.test.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get.test.ts index 7301a3cf51974..7e180f355ddfd 100644 --- a/x-pack/plugins/security/server/routes/authorization/privileges/get.test.ts +++ b/x-pack/plugins/security/server/routes/authorization/privileges/get.test.ts @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { kibanaResponseFactory, RequestHandlerContext } from '../../../../../../../src/core/server'; +import { kibanaResponseFactory } from '../../../../../../../src/core/server'; import { LicenseCheck } from '../../../../../licensing/server'; import { RawKibanaPrivileges } from '../../../../common/model'; import { defineGetPrivilegesRoutes } from './get'; +import type { SecurityRequestHandlerContext } from '../../../types'; import { httpServerMock } from '../../../../../../../src/core/server/mocks'; import { routeDefinitionParamsMock } from '../../index.mock'; @@ -66,7 +67,7 @@ describe('GET privileges', () => { }); const mockContext = ({ licensing: { license: { check: jest.fn().mockReturnValue(licenseCheckResult) } }, - } as unknown) as RequestHandlerContext; + } as unknown) as SecurityRequestHandlerContext; const response = await handler(mockContext, mockRequest, kibanaResponseFactory); expect(response.status).toBe(asserts.statusCode); diff --git a/x-pack/plugins/security/server/routes/authorization/spaces/share_saved_object_permissions.test.ts b/x-pack/plugins/security/server/routes/authorization/spaces/share_saved_object_permissions.test.ts index ccdee8b100039..c3ceecef1fa68 100644 --- a/x-pack/plugins/security/server/routes/authorization/spaces/share_saved_object_permissions.test.ts +++ b/x-pack/plugins/security/server/routes/authorization/spaces/share_saved_object_permissions.test.ts @@ -5,10 +5,8 @@ */ import { - IRouter, kibanaResponseFactory, RequestHandler, - RequestHandlerContext, RouteConfig, } from '../../../../../../../src/core/server'; import { defineShareSavedObjectPermissionRoutes } from './share_saved_object_permissions'; @@ -18,26 +16,27 @@ import { routeDefinitionParamsMock } from '../../index.mock'; import { RouteDefinitionParams } from '../..'; import { DeeplyMockedKeys } from '@kbn/utility-types/target/jest'; import { CheckPrivileges } from '../../../authorization/types'; +import type { SecurityRequestHandlerContext, SecurityRouter } from '../../../types'; describe('Share Saved Object Permissions', () => { - let router: jest.Mocked; + let router: jest.Mocked; let routeParamsMock: DeeplyMockedKeys; const mockContext = ({ licensing: { license: { check: jest.fn().mockReturnValue({ state: 'valid' }) }, }, - } as unknown) as RequestHandlerContext; + } as unknown) as SecurityRequestHandlerContext; beforeEach(() => { routeParamsMock = routeDefinitionParamsMock.create(); - router = routeParamsMock.router as jest.Mocked; + router = routeParamsMock.router as jest.Mocked; defineShareSavedObjectPermissionRoutes(routeParamsMock); }); describe('GET /internal/security/_share_saved_object_permissions', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [shareRouteConfig, shareRouteHandler] = router.get.mock.calls.find( diff --git a/x-pack/plugins/security/server/routes/index.ts b/x-pack/plugins/security/server/routes/index.ts index 899215c49fa9f..2d49329fd63d3 100644 --- a/x-pack/plugins/security/server/routes/index.ts +++ b/x-pack/plugins/security/server/routes/index.ts @@ -5,13 +5,14 @@ */ import type { PublicMethodsOf } from '@kbn/utility-types'; import type { KibanaFeature } from '../../../features/server'; -import type { HttpResources, IBasePath, IRouter, Logger } from '../../../../../src/core/server'; +import type { HttpResources, IBasePath, Logger } from '../../../../../src/core/server'; import type { SecurityLicense } from '../../common/licensing'; import type { AuthenticationServiceStart } from '../authentication'; import type { AuthorizationServiceSetup } from '../authorization'; import type { ConfigType } from '../config'; import type { SecurityFeatureUsageServiceStart } from '../feature_usage'; import type { Session } from '../session_management'; +import type { SecurityRouter } from '../types'; import { defineAuthenticationRoutes } from './authentication'; import { defineAuthorizationRoutes } from './authorization'; @@ -26,7 +27,7 @@ import { defineViewRoutes } from './views'; * Describes parameters used to define HTTP routes. */ export interface RouteDefinitionParams { - router: IRouter; + router: SecurityRouter; basePath: IBasePath; httpResources: HttpResources; logger: Logger; diff --git a/x-pack/plugins/security/server/routes/licensed_route_handler.ts b/x-pack/plugins/security/server/routes/licensed_route_handler.ts index d8c212aa2d217..c1722c5b19833 100644 --- a/x-pack/plugins/security/server/routes/licensed_route_handler.ts +++ b/x-pack/plugins/security/server/routes/licensed_route_handler.ts @@ -5,17 +5,19 @@ */ import { KibanaResponseFactory, RequestHandler, RouteMethod } from 'kibana/server'; +import type { SecurityRequestHandlerContext } from '../types'; export const createLicensedRouteHandler = < P, Q, B, + Context extends SecurityRequestHandlerContext, M extends RouteMethod, R extends KibanaResponseFactory >( - handler: RequestHandler + handler: RequestHandler ) => { - const licensedRouteHandler: RequestHandler = ( + const licensedRouteHandler: RequestHandler = ( context, request, responseToolkit diff --git a/x-pack/plugins/security/server/routes/session_management/extend.test.ts b/x-pack/plugins/security/server/routes/session_management/extend.test.ts index 235fce152510c..8307905fb8842 100644 --- a/x-pack/plugins/security/server/routes/session_management/extend.test.ts +++ b/x-pack/plugins/security/server/routes/session_management/extend.test.ts @@ -5,19 +5,18 @@ */ import { - IRouter, kibanaResponseFactory, RequestHandler, - RequestHandlerContext, RouteConfig, } from '../../../../../../src/core/server'; import { defineSessionExtendRoutes } from './extend'; import { httpServerMock } from '../../../../../../src/core/server/mocks'; +import type { SecurityRequestHandlerContext, SecurityRouter } from '../../types'; import { routeDefinitionParamsMock } from '../index.mock'; describe('Extend session routes', () => { - let router: jest.Mocked; + let router: jest.Mocked; beforeEach(() => { const routeParamsMock = routeDefinitionParamsMock.create(); router = routeParamsMock.router; @@ -26,7 +25,7 @@ describe('Extend session routes', () => { }); describe('extend session', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [extendRouteConfig, extendRouteHandler] = router.post.mock.calls.find( @@ -45,7 +44,7 @@ describe('Extend session routes', () => { it('always returns 302.', async () => { await expect( routeHandler( - ({} as unknown) as RequestHandlerContext, + ({} as unknown) as SecurityRequestHandlerContext, httpServerMock.createKibanaRequest(), kibanaResponseFactory ) diff --git a/x-pack/plugins/security/server/routes/session_management/info.test.ts b/x-pack/plugins/security/server/routes/session_management/info.test.ts index a104336f2e6ba..c51956f3fe530 100644 --- a/x-pack/plugins/security/server/routes/session_management/info.test.ts +++ b/x-pack/plugins/security/server/routes/session_management/info.test.ts @@ -5,22 +5,21 @@ */ import { - IRouter, kibanaResponseFactory, RequestHandler, - RequestHandlerContext, RouteConfig, } from '../../../../../../src/core/server'; import type { PublicMethodsOf } from '@kbn/utility-types'; import { Session } from '../../session_management'; import { defineSessionInfoRoutes } from './info'; +import type { SecurityRequestHandlerContext, SecurityRouter } from '../../types'; import { httpServerMock } from '../../../../../../src/core/server/mocks'; import { sessionMock } from '../../session_management/session.mock'; import { routeDefinitionParamsMock } from '../index.mock'; describe('Info session routes', () => { - let router: jest.Mocked; + let router: jest.Mocked; let session: jest.Mocked>; beforeEach(() => { const routeParamsMock = routeDefinitionParamsMock.create(); @@ -31,7 +30,7 @@ describe('Info session routes', () => { }); describe('extend session', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [extendRouteConfig, extendRouteHandler] = router.get.mock.calls.find( @@ -53,7 +52,11 @@ describe('Info session routes', () => { const request = httpServerMock.createKibanaRequest(); await expect( - routeHandler(({} as unknown) as RequestHandlerContext, request, kibanaResponseFactory) + routeHandler( + ({} as unknown) as SecurityRequestHandlerContext, + request, + kibanaResponseFactory + ) ).resolves.toEqual({ status: 500, options: {}, @@ -79,7 +82,7 @@ describe('Info session routes', () => { }; await expect( routeHandler( - ({} as unknown) as RequestHandlerContext, + ({} as unknown) as SecurityRequestHandlerContext, httpServerMock.createKibanaRequest(), kibanaResponseFactory ) @@ -95,7 +98,7 @@ describe('Info session routes', () => { await expect( routeHandler( - ({} as unknown) as RequestHandlerContext, + ({} as unknown) as SecurityRequestHandlerContext, httpServerMock.createKibanaRequest(), kibanaResponseFactory ) diff --git a/x-pack/plugins/security/server/routes/users/change_password.test.ts b/x-pack/plugins/security/server/routes/users/change_password.test.ts index 1ef4e407e45e2..24e73e456619b 100644 --- a/x-pack/plugins/security/server/routes/users/change_password.test.ts +++ b/x-pack/plugins/security/server/routes/users/change_password.test.ts @@ -8,12 +8,11 @@ import { errors } from 'elasticsearch'; import { ObjectType } from '@kbn/config-schema'; import type { PublicMethodsOf } from '@kbn/utility-types'; import type { DeeplyMockedKeys } from '@kbn/utility-types/jest'; +import type { SecurityRequestHandlerContext, SecurityRouter } from '../../types'; import { Headers, - IRouter, kibanaResponseFactory, RequestHandler, - RequestHandlerContext, RouteConfig, } from '../../../../../../src/core/server'; import { AuthenticationResult, AuthenticationServiceStart } from '../../authentication'; @@ -27,12 +26,12 @@ import { routeDefinitionParamsMock } from '../index.mock'; import { authenticationServiceMock } from '../../authentication/authentication_service.mock'; describe('Change password', () => { - let router: jest.Mocked; + let router: jest.Mocked; let authc: DeeplyMockedKeys; let session: jest.Mocked>; - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; - let mockContext: DeeplyMockedKeys; + let mockContext: DeeplyMockedKeys; function checkPasswordChangeAPICall(username: string, headers?: Headers) { expect( diff --git a/x-pack/plugins/security/server/routes/views/access_agreement.test.ts b/x-pack/plugins/security/server/routes/views/access_agreement.test.ts index dfe5faa95ae15..4c4f8a22eee23 100644 --- a/x-pack/plugins/security/server/routes/views/access_agreement.test.ts +++ b/x-pack/plugins/security/server/routes/views/access_agreement.test.ts @@ -8,16 +8,15 @@ import { RequestHandler, RouteConfig, kibanaResponseFactory, - IRouter, HttpResources, HttpResourcesRequestHandler, - RequestHandlerContext, } from '../../../../../../src/core/server'; import { SecurityLicense, SecurityLicenseFeatures } from '../../../common/licensing'; import type { AuthenticationProvider } from '../../../common/model'; import { ConfigType } from '../../config'; import { Session } from '../../session_management'; import { defineAccessAgreementRoutes } from './access_agreement'; +import type { SecurityRouter, SecurityRequestHandlerContext } from '../../types'; import { httpResourcesMock, httpServerMock } from '../../../../../../src/core/server/mocks'; import { sessionMock } from '../../session_management/session.mock'; @@ -25,11 +24,11 @@ import { routeDefinitionParamsMock } from '../index.mock'; describe('Access agreement view routes', () => { let httpResources: jest.Mocked; - let router: jest.Mocked; + let router: jest.Mocked; let config: ConfigType; let session: jest.Mocked>; let license: jest.Mocked; - let mockContext: RequestHandlerContext; + let mockContext: SecurityRequestHandlerContext; beforeEach(() => { const routeParamsMock = routeDefinitionParamsMock.create(); router = routeParamsMock.router; @@ -46,7 +45,7 @@ describe('Access agreement view routes', () => { licensing: { license: { check: jest.fn().mockReturnValue({ check: 'valid' }) }, }, - } as unknown) as RequestHandlerContext; + } as unknown) as SecurityRequestHandlerContext; defineAccessAgreementRoutes(routeParamsMock); }); @@ -93,7 +92,7 @@ describe('Access agreement view routes', () => { }); describe('Access agreement state route', () => { - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [loginStateRouteConfig, loginStateRouteHandler] = router.get.mock.calls.find( diff --git a/x-pack/plugins/security/server/routes/views/capture_url.test.ts b/x-pack/plugins/security/server/routes/views/capture_url.test.ts index 2b2aab3407eb3..74a30cfb24654 100644 --- a/x-pack/plugins/security/server/routes/views/capture_url.test.ts +++ b/x-pack/plugins/security/server/routes/views/capture_url.test.ts @@ -9,12 +9,12 @@ import { RouteConfig, HttpResources, HttpResourcesRequestHandler, - RequestHandlerContext, } from '../../../../../../src/core/server'; import { defineCaptureURLRoutes } from './capture_url'; import { httpResourcesMock, httpServerMock } from '../../../../../../src/core/server/mocks'; import { routeDefinitionParamsMock } from '../index.mock'; +import type { SecurityRequestHandlerContext } from '../../types'; describe('Capture URL view routes', () => { let httpResources: jest.Mocked; @@ -92,7 +92,7 @@ describe('Capture URL view routes', () => { const request = httpServerMock.createKibanaRequest(); const responseFactory = httpResourcesMock.createResponseFactory(); - await routeHandler(({} as unknown) as RequestHandlerContext, request, responseFactory); + await routeHandler(({} as unknown) as SecurityRequestHandlerContext, request, responseFactory); expect(responseFactory.renderAnonymousCoreApp).toHaveBeenCalledWith(); }); diff --git a/x-pack/plugins/security/server/routes/views/login.test.ts b/x-pack/plugins/security/server/routes/views/login.test.ts index e79420fa05daf..dfaf935f64972 100644 --- a/x-pack/plugins/security/server/routes/views/login.test.ts +++ b/x-pack/plugins/security/server/routes/views/login.test.ts @@ -9,7 +9,6 @@ import { Type } from '@kbn/config-schema'; import { HttpResources, HttpResourcesRequestHandler, - IRouter, RequestHandler, kibanaResponseFactory, RouteConfig, @@ -18,6 +17,7 @@ import { SecurityLicense } from '../../../common/licensing'; import { LoginSelectorProvider } from '../../../common/login_state'; import { ConfigType } from '../../config'; import { defineLoginRoutes } from './login'; +import type { SecurityRouter, SecurityRequestHandlerContext } from '../../types'; import { coreMock, @@ -28,7 +28,7 @@ import { routeDefinitionParamsMock } from '../index.mock'; describe('Login view routes', () => { let httpResources: jest.Mocked; - let router: jest.Mocked; + let router: jest.Mocked; let license: jest.Mocked; let config: ConfigType; beforeEach(() => { @@ -145,7 +145,7 @@ describe('Login view routes', () => { return routeDefinitionParamsMock.create({ authc: { ...authcConfig } }).config.authc; } - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; let routeConfig: RouteConfig; beforeEach(() => { const [loginStateRouteConfig, loginStateRouteHandler] = router.get.mock.calls.find( diff --git a/x-pack/plugins/security/server/types.ts b/x-pack/plugins/security/server/types.ts new file mode 100644 index 0000000000000..74c4c6b9cab7f --- /dev/null +++ b/x-pack/plugins/security/server/types.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 type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; + +/** + * @internal + */ +export interface SecurityRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; +} + +/** + * @internal + */ +export type SecurityRouter = IRouter; diff --git a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts index d2ce0908b91fc..d287ada74eebc 100644 --- a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts @@ -15,7 +15,7 @@ import { getPackagePolicyCreateCallback, getPackagePolicyUpdateCallback, } from './ingest_integration'; -import { KibanaRequest, RequestHandlerContext } from 'kibana/server'; +import { KibanaRequest } from 'kibana/server'; import { createMockConfig, requestContextMock } from '../lib/detection_engine/routes/__mocks__'; import { EndpointAppContextServiceStartContract } from './endpoint_app_context_services'; import { createMockEndpointAppContextServiceStartContract } from './mocks'; @@ -25,13 +25,14 @@ import { Subject } from 'rxjs'; import { ILicense } from '../../../licensing/common/types'; import { EndpointDocGenerator } from '../../common/endpoint/generate_data'; import { ProtectionModes } from '../../common/endpoint/types'; +import type { SecuritySolutionRequestHandlerContext } from '../types'; import { getExceptionListClientMock } from '../../../lists/server/services/exception_lists/exception_list_client.mock'; import { ExceptionListClient } from '../../../lists/server'; describe('ingest_integration tests ', () => { let endpointAppContextMock: EndpointAppContextServiceStartContract; let req: KibanaRequest; - let ctx: RequestHandlerContext; + let ctx: SecuritySolutionRequestHandlerContext; const exceptionListClient: ExceptionListClient = getExceptionListClientMock(); const maxTimelineImportExportSize = createMockConfig().maxTimelineImportExportSize; let licenseEmitter: Subject; diff --git a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts index 194d93df4b43b..1e7f440ed6788 100644 --- a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts +++ b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts @@ -100,10 +100,15 @@ export const getPackagePolicyCreateCallback = ( // prep for detection rules creation const appClient = appClientFactory.create(request); + // This callback is called by fleet plugin. + // It doesn't have access to SecuritySolutionRequestHandlerContext in runtime. + // Muting the error to have green CI. + // @ts-expect-error const frameworkRequest = await buildFrameworkRequest(context, securitySetup, request); // Create detection index & rules (if necessary). move past any failure, this is just a convenience try { + // @ts-expect-error await createDetectionIndex(context, appClient); } catch (err) { if (err.statusCode !== 409) { @@ -117,6 +122,7 @@ export const getPackagePolicyCreateCallback = ( // this checks to make sure index exists first, safe to try in case of failure above // may be able to recover from minor errors await createPrepackagedRules( + // @ts-expect-error context, appClient, alerts.getAlertsClientWithRequest(request), diff --git a/x-pack/plugins/security_solution/server/endpoint/mocks.ts b/x-pack/plugins/security_solution/server/endpoint/mocks.ts index 2161ccf0eb780..04bca2f0627b5 100644 --- a/x-pack/plugins/security_solution/server/endpoint/mocks.ts +++ b/x-pack/plugins/security_solution/server/endpoint/mocks.ts @@ -28,6 +28,7 @@ import { EndpointAppContext } from './types'; import { MetadataRequestContext } from './routes/metadata/handlers'; // import { licenseMock } from '../../../licensing/common/licensing.mock'; import { LicenseService } from '../../common/license/license'; +import { SecuritySolutionRequestHandlerContext } from '../types'; /** * Creates a mocked EndpointAppContext. @@ -118,7 +119,7 @@ export const createMockMetadataRequestContext = (): jest.Mocked, }; }; diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts index 4454da855569b..cb26339e3b0f0 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts @@ -5,7 +5,7 @@ */ import { deflateSync, inflateSync } from 'zlib'; import LRU from 'lru-cache'; -import { +import type { ILegacyClusterClient, IRouter, SavedObjectsClientContract, @@ -13,7 +13,6 @@ import { RouteConfig, RequestHandler, KibanaResponseFactory, - RequestHandlerContext, SavedObject, } from 'kibana/server'; import { @@ -29,6 +28,7 @@ import { EndpointAppContextService } from '../../endpoint_app_context_services'; import { createMockEndpointAppContextServiceStartContract } from '../../mocks'; import { createMockConfig } from '../../../lib/detection_engine/routes/__mocks__'; import { WrappedTranslatedExceptionList } from '../../schemas/artifacts/lists'; +import type { SecuritySolutionRequestHandlerContext } from '../../../types'; const mockArtifactName = `${ArtifactConstants.GLOBAL_ALLOWLIST_NAME}-windows-v1`; const expectedEndpointExceptions: WrappedTranslatedExceptionList = { @@ -173,7 +173,7 @@ describe('test alerts route', () => { client: mockSavedObjectClient, }, }, - } as unknown) as RequestHandlerContext, + } as unknown) as SecuritySolutionRequestHandlerContext, mockRequest, mockResponse ); @@ -217,7 +217,7 @@ describe('test alerts route', () => { client: mockSavedObjectClient, }, }, - } as unknown) as RequestHandlerContext, + } as unknown) as SecuritySolutionRequestHandlerContext, mockRequest, mockResponse ); @@ -251,7 +251,7 @@ describe('test alerts route', () => { client: mockSavedObjectClient, }, }, - } as unknown) as RequestHandlerContext, + } as unknown) as SecuritySolutionRequestHandlerContext, mockRequest, mockResponse ); @@ -279,7 +279,7 @@ describe('test alerts route', () => { client: mockSavedObjectClient, }, }, - } as unknown) as RequestHandlerContext, + } as unknown) as SecuritySolutionRequestHandlerContext, mockRequest, mockResponse ); @@ -313,7 +313,7 @@ describe('test alerts route', () => { client: mockSavedObjectClient, }, }, - } as unknown) as RequestHandlerContext, + } as unknown) as SecuritySolutionRequestHandlerContext, mockRequest, mockResponse ); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts index 83732170fb5c3..4a94e24224397 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts @@ -5,7 +5,7 @@ */ import Boom from '@hapi/boom'; -import { RequestHandlerContext, Logger, RequestHandler } from 'kibana/server'; +import type { Logger, RequestHandler } from 'kibana/server'; import { TypeOf } from '@kbn/config-schema'; import { HostInfo, @@ -14,6 +14,8 @@ import { HostStatus, MetadataQueryStrategyVersions, } from '../../../../common/endpoint/types'; +import type { SecuritySolutionRequestHandlerContext } from '../../../types'; + import { getESQueryHostMetadataByID, kibanaRequestToMetadataListESQuery } from './query_builders'; import { Agent, AgentStatus, PackagePolicy } from '../../../../../fleet/common/types/models'; import { EndpointAppContext, HostListQueryResult } from '../../types'; @@ -25,7 +27,7 @@ import { EndpointAppContextService } from '../../endpoint_app_context_services'; export interface MetadataRequestContext { endpointAppContextService: EndpointAppContextService; logger: Logger; - requestHandlerContext: RequestHandlerContext; + requestHandlerContext: SecuritySolutionRequestHandlerContext; } const HOST_STATUS_MAPPING = new Map([ @@ -52,7 +54,12 @@ export const getMetadataListRequestHandler = function ( endpointAppContext: EndpointAppContext, logger: Logger, queryStrategyVersion?: MetadataQueryStrategyVersions -): RequestHandler> { +): RequestHandler< + unknown, + unknown, + TypeOf, + SecuritySolutionRequestHandlerContext +> { return async (context, request, response) => { try { const agentService = endpointAppContext.service.getAgentService(); @@ -112,7 +119,12 @@ export const getMetadataRequestHandler = function ( endpointAppContext: EndpointAppContext, logger: Logger, queryStrategyVersion?: MetadataQueryStrategyVersions -): RequestHandler, undefined, undefined> { +): RequestHandler< + TypeOf, + unknown, + unknown, + SecuritySolutionRequestHandlerContext +> { return async (context, request, response) => { const agentService = endpointAppContext.service.getAgentService(); if (agentService === undefined) { diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts index bfb2a6a828e68..6bcde49ea80b4 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { HostStatus, MetadataQueryStrategyVersions } from '../../../../common/endpoint/types'; import { EndpointAppContext } from '../../types'; import { getLogger, getMetadataListRequestHandler, getMetadataRequestHandler } from './handlers'; +import type { SecuritySolutionPluginRouter } from '../../../types'; export const BASE_ENDPOINT_ROUTE = '/api/endpoint'; export const METADATA_REQUEST_V1_ROUTE = `${BASE_ENDPOINT_ROUTE}/v1/metadata`; @@ -60,7 +60,10 @@ export const GetMetadataListRequestSchema = { ), }; -export function registerEndpointRoutes(router: IRouter, endpointAppContext: EndpointAppContext) { +export function registerEndpointRoutes( + router: SecuritySolutionPluginRouter, + endpointAppContext: EndpointAppContext +) { const logger = getLogger(endpointAppContext); router.post( { diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts index 25de64aac5258..5049104a96401 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts @@ -5,7 +5,6 @@ */ import { ILegacyClusterClient, - IRouter, ILegacyScopedClusterClient, KibanaResponseFactory, RequestHandler, @@ -43,16 +42,17 @@ import { import { createV1SearchResponse, createV2SearchResponse } from './support/test_support'; import { PackageService } from '../../../../../fleet/server/services'; import { metadataTransformPrefix } from '../../../../common/endpoint/constants'; +import type { SecuritySolutionPluginRouter } from '../../../types'; describe('test endpoint route', () => { - let routerMock: jest.Mocked; + let routerMock: jest.Mocked; let mockResponse: jest.Mocked; let mockClusterClient: jest.Mocked; let mockScopedClient: jest.Mocked; let mockSavedObjectClient: jest.Mocked; let mockPackageService: jest.Mocked; // eslint-disable-next-line @typescript-eslint/no-explicit-any - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; // eslint-disable-next-line @typescript-eslint/no-explicit-any let routeConfig: RouteConfig; // tests assume that fleet is enabled, and thus agentService is available diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata_v1.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata_v1.test.ts index 44776bfddd61a..b879272862d48 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata_v1.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata_v1.test.ts @@ -5,7 +5,6 @@ */ import { ILegacyClusterClient, - IRouter, ILegacyScopedClusterClient, KibanaResponseFactory, RequestHandler, @@ -38,16 +37,17 @@ import { EndpointDocGenerator } from '../../../../common/endpoint/generate_data' import { Agent, EsAssetReference } from '../../../../../fleet/common/types/models'; import { createV1SearchResponse } from './support/test_support'; import { PackageService } from '../../../../../fleet/server/services'; +import type { SecuritySolutionPluginRouter } from '../../../types'; describe('test endpoint route v1', () => { - let routerMock: jest.Mocked; + let routerMock: jest.Mocked; let mockResponse: jest.Mocked; let mockClusterClient: jest.Mocked; let mockScopedClient: jest.Mocked; let mockSavedObjectClient: jest.Mocked; let mockPackageService: jest.Mocked; // eslint-disable-next-line @typescript-eslint/no-explicit-any - let routeHandler: RequestHandler; + let routeHandler: RequestHandler; // eslint-disable-next-line @typescript-eslint/no-explicit-any let routeConfig: RouteConfig; // tests assume that fleet is enabled, and thus agentService is available diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.test.ts index de78313c6ca2b..feee872b90acd 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.test.ts @@ -22,6 +22,7 @@ import { getTrustedAppsListRouteHandler, getTrustedAppsSummaryRouteHandler, } from './handlers'; +import type { SecuritySolutionRequestHandlerContext } from '../../../types'; const exceptionsListClient = listMock.getExceptionListClient() as jest.Mocked; @@ -31,13 +32,14 @@ const createAppContextMock = () => ({ config: () => Promise.resolve(createMockConfig()), }); -const createHandlerContextMock = () => ({ - ...xpackMocks.createRequestHandlerContext(), - lists: { - getListClient: jest.fn(), - getExceptionListClient: jest.fn().mockReturnValue(exceptionsListClient), - }, -}); +const createHandlerContextMock = () => + (({ + ...xpackMocks.createRequestHandlerContext(), + lists: { + getListClient: jest.fn(), + getExceptionListClient: jest.fn().mockReturnValue(exceptionsListClient), + }, + } as unknown) as jest.Mocked); const assertResponse = ( response: jest.Mocked, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.ts b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.ts index aa2167a493294..825ae57b2fa44 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/handlers.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandler, RequestHandlerContext } from 'kibana/server'; +import type { RequestHandler } from 'kibana/server'; +import type { SecuritySolutionRequestHandlerContext } from '../../../types'; import { ExceptionListClient } from '../../../../../lists/server'; @@ -23,7 +24,9 @@ import { MissingTrustedAppException, } from './service'; -const exceptionListClientFromContext = (context: RequestHandlerContext): ExceptionListClient => { +const exceptionListClientFromContext = ( + context: SecuritySolutionRequestHandlerContext +): ExceptionListClient => { const exceptionLists = context.lists?.getExceptionListClient(); if (!exceptionLists) { @@ -35,7 +38,12 @@ const exceptionListClientFromContext = (context: RequestHandlerContext): Excepti export const getTrustedAppsDeleteRouteHandler = ( endpointAppContext: EndpointAppContext -): RequestHandler => { +): RequestHandler< + DeleteTrustedAppsRequestParams, + unknown, + unknown, + SecuritySolutionRequestHandlerContext +> => { const logger = endpointAppContext.logFactory.get('trusted_apps'); return async (context, req, res) => { @@ -56,7 +64,12 @@ export const getTrustedAppsDeleteRouteHandler = ( export const getTrustedAppsListRouteHandler = ( endpointAppContext: EndpointAppContext -): RequestHandler => { +): RequestHandler< + unknown, + GetTrustedAppsListRequest, + unknown, + SecuritySolutionRequestHandlerContext +> => { const logger = endpointAppContext.logFactory.get('trusted_apps'); return async (context, req, res) => { @@ -73,7 +86,12 @@ export const getTrustedAppsListRouteHandler = ( export const getTrustedAppsCreateRouteHandler = ( endpointAppContext: EndpointAppContext -): RequestHandler => { +): RequestHandler< + unknown, + unknown, + PostTrustedAppCreateRequest, + SecuritySolutionRequestHandlerContext +> => { const logger = endpointAppContext.logFactory.get('trusted_apps'); return async (context, req, res) => { @@ -90,7 +108,12 @@ export const getTrustedAppsCreateRouteHandler = ( export const getTrustedAppsSummaryRouteHandler = ( endpointAppContext: EndpointAppContext -): RequestHandler => { +): RequestHandler< + unknown, + unknown, + PostTrustedAppCreateRequest, + SecuritySolutionRequestHandlerContext +> => { const logger = endpointAppContext.logFactory.get('trusted_apps'); return async (context, req, res) => { diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/index.ts index ce5f571ce9be3..7e318030f1f75 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/index.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; import { DeleteTrustedAppsRequestSchema, GetTrustedAppsRequestSchema, @@ -23,9 +22,10 @@ import { getTrustedAppsSummaryRouteHandler, } from './handlers'; import { EndpointAppContext } from '../../types'; +import { SecuritySolutionPluginRouter } from '../../../types'; export const registerTrustedAppsRoutes = ( - router: IRouter, + router: SecuritySolutionPluginRouter, endpointAppContext: EndpointAppContext ) => { // DELETE one diff --git a/x-pack/plugins/security_solution/server/index.ts b/x-pack/plugins/security_solution/server/index.ts index 94764fd159360..0fa037ca77d04 100644 --- a/x-pack/plugins/security_solution/server/index.ts +++ b/x-pack/plugins/security_solution/server/index.ts @@ -57,3 +57,4 @@ export { getIndexExists } from './lib/detection_engine/index/get_index_exists'; export { buildRouteValidation } from './utils/build_validation/route_validation'; export { transformError, buildSiemResponse } from './lib/detection_engine/routes/utils'; export { readPrivileges } from './lib/detection_engine/privileges/read_privileges'; +export type { AppRequestContext } from './types'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts index 8e379e5caa89e..511897094a1ec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandlerContext } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionRequestHandlerContext } from '../../../../types'; import { coreMock, elasticsearchServiceMock, @@ -40,7 +40,7 @@ const createRequestContextMock = ( }, licensing: clients.licensing, securitySolution: { getAppClient: jest.fn(() => clients.appClient) }, - } as unknown) as RequestHandlerContext; + } as unknown) as SecuritySolutionRequestHandlerContext; }; const createTools = () => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/server.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/server.ts index d0683f3baabe9..37b18fbcc2b07 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/server.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/server.ts @@ -8,13 +8,13 @@ import { RequestHandler, RouteConfig, KibanaRequest, - RequestHandlerContext, } from '../../../../../../../../src/core/server'; import { httpServiceMock } from '../../../../../../../../src/core/server/mocks'; import { requestContextMock } from './request_context'; import { responseMock as responseFactoryMock } from './response_factory'; import { requestMock } from '.'; import { responseAdapter } from './test_adapters'; +import { SecuritySolutionRequestHandlerContext } from '../../../../types'; interface Route { config: RouteConfig; @@ -53,7 +53,10 @@ class MockServer { return this.resultMock; } - public async inject(request: KibanaRequest, context: RequestHandlerContext = this.contextMock) { + public async inject( + request: KibanaRequest, + context: SecuritySolutionRequestHandlerContext = this.contextMock + ) { const validatedRequest = this.validateRequest(request); const [rejection] = this.resultMock.badRequest.mock.calls; if (rejection) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts index 8280e86bdf2cc..81be361ed4856 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts @@ -4,8 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AppClient } from '../../../../types'; -import { IRouter, RequestHandlerContext } from '../../../../../../../../src/core/server'; +import type { + AppClient, + SecuritySolutionPluginRouter, + SecuritySolutionRequestHandlerContext, +} from '../../../../types'; import { DETECTION_ENGINE_INDEX_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { getIndexExists } from '../../index/get_index_exists'; @@ -20,7 +23,7 @@ import { templateNeedsUpdate } from './check_template_version'; import { getIndexVersion } from './get_index_version'; import { isOutdated } from '../../migrations/helpers'; -export const createIndexRoute = (router: IRouter) => { +export const createIndexRoute = (router: SecuritySolutionPluginRouter) => { router.post( { path: DETECTION_ENGINE_INDEX_URL, @@ -59,7 +62,7 @@ class CreateIndexError extends Error { } export const createDetectionIndex = async ( - context: RequestHandlerContext, + context: SecuritySolutionRequestHandlerContext, siemClient: AppClient ): Promise => { const clusterClient = context.core.elasticsearch.legacy.client; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts index b58103bf15f3b..6b9a96b5efe2c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_INDEX_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { getIndexExists } from '../../index/get_index_exists'; @@ -24,7 +24,7 @@ import { deleteTemplate } from '../../index/delete_template'; * * And ensuring they're all gone */ -export const deleteIndexRoute = (router: IRouter) => { +export const deleteIndexRoute = (router: SecuritySolutionPluginRouter) => { router.delete( { path: DETECTION_ENGINE_INDEX_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts index d898d3fd59240..908313ad88e3c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_INDEX_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { getIndexExists } from '../../index/get_index_exists'; @@ -12,7 +12,7 @@ import { SIGNALS_TEMPLATE_VERSION } from './get_signals_template'; import { getIndexVersion } from './get_index_version'; import { isOutdated } from '../../migrations/helpers'; -export const readIndexRoute = (router: IRouter) => { +export const readIndexRoute = (router: SecuritySolutionPluginRouter) => { router.get( { path: DETECTION_ENGINE_INDEX_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts index 945be0c584134..76e68d3cd9b33 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts @@ -74,6 +74,7 @@ describe('read_privileges route', () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; const response = await server.inject( getPrivilegeRequest({ auth: { isAuthenticated: false } }), + // @ts-expect-error contextWithoutSecuritySolution ); expect(response.status).toEqual(404); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts index 174aa4911ba1e..58d8ef26faff6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts @@ -6,12 +6,15 @@ import { merge } from 'lodash/fp'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_PRIVILEGES_URL } from '../../../../../common/constants'; import { buildSiemResponse, transformError } from '../utils'; import { readPrivileges } from '../../privileges/read_privileges'; -export const readPrivilegesRoute = (router: IRouter, usingEphemeralEncryptionKey: boolean) => { +export const readPrivilegesRoute = ( + router: SecuritySolutionPluginRouter, + usingEphemeralEncryptionKey: boolean +) => { router.get( { path: DETECTION_ENGINE_PRIVILEGES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts index 3dc25583579c5..a4c35c87ca3bc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts @@ -141,6 +141,7 @@ describe('add_prepackaged_rules_route', () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; const response = await server.inject( addPrepackagedRulesRequest(), + // @ts-expect-error contextWithoutSecuritySolution ); expect(response.status).toEqual(404); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index 210ec87ade2dc..a360d43d5016d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -4,8 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AppClient } from '../../../../types'; -import { IRouter, RequestHandlerContext } from '../../../../../../../../src/core/server'; +import type { + AppClient, + SecuritySolutionPluginRouter, + SecuritySolutionRequestHandlerContext, +} from '../../../../types'; import { validate } from '../../../../../common/validate'; import { @@ -35,7 +38,7 @@ import { FrameworkRequest } from '../../../framework'; import { ExceptionListClient } from '../../../../../../lists/server'; export const addPrepackedRulesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { @@ -87,7 +90,7 @@ class PrepackagedRulesError extends Error { } export const createPrepackagedRules = async ( - context: RequestHandlerContext, + context: SecuritySolutionRequestHandlerContext, siemClient: AppClient, alertsClient: AlertsClient, frameworkRequest: FrameworkRequest, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts index 55317fc28afca..31dca3646231d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts @@ -54,6 +54,7 @@ describe('create_rules_bulk', () => { it('returns 404 if siem client is unavailable', async () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; + // @ts-expect-error const response = await server.inject(getReadBulkRequest(), contextWithoutSecuritySolution); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts index 3473948b000c7..6795abc5c211c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts @@ -8,7 +8,7 @@ import { validate } from '../../../../../common/validate'; import { createRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/create_rules_type_dependents'; import { createRulesBulkSchema } from '../../../../../common/detection_engine/schemas/request/create_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; @@ -25,7 +25,10 @@ import { convertCreateAPIToInternalSchema } from '../../schemas/rule_converters' import { RuleTypeParams } from '../../types'; import { Alert } from '../../../../../../alerts/common'; -export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => { +export const createRulesBulkRoute = ( + router: SecuritySolutionPluginRouter, + ml: SetupPlugins['ml'] +) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_create`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts index 40465f4dc7456..4f85ecb789a57 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts @@ -63,6 +63,7 @@ describe('create_rules', () => { it('returns 404 if siem client is unavailable', async () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; + // @ts-expect-error const response = await server.inject(getCreateRequest(), contextWithoutSecuritySolution); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts index c59d5d2a36fd5..bfe32b9ae9a02 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts @@ -5,9 +5,9 @@ */ import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { readRules } from '../../rules/read_rules'; @@ -22,7 +22,10 @@ import { convertCreateAPIToInternalSchema } from '../../schemas/rule_converters' import { RuleTypeParams } from '../../types'; import { Alert } from '../../../../../../alerts/common'; -export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void => { +export const createRulesRoute = ( + router: SecuritySolutionPluginRouter, + ml: SetupPlugins['ml'] +): void => { router.post( { path: DETECTION_ENGINE_RULES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts index 99bf16aadc815..f4d9ac0a4ee84 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts @@ -12,7 +12,11 @@ import { QueryRulesBulkSchemaDecoded, } from '../../../../../common/detection_engine/schemas/request/query_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; -import { IRouter, RouteConfig, RequestHandler } from '../../../../../../../../src/core/server'; +import type { RouteConfig, RequestHandler } from '../../../../../../../../src/core/server'; +import type { + SecuritySolutionPluginRouter, + SecuritySolutionRequestHandlerContext, +} from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { getIdBulkError } from './utils'; import { transformValidateBulkError } from './validate'; @@ -23,9 +27,15 @@ import { deleteRuleActionsSavedObject } from '../../rule_actions/delete_rule_act import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; type Config = RouteConfig; -type Handler = RequestHandler; +type Handler = RequestHandler< + unknown, + unknown, + QueryRulesBulkSchemaDecoded, + SecuritySolutionRequestHandlerContext, + 'delete' | 'post' +>; -export const deleteRulesBulkRoute = (router: IRouter) => { +export const deleteRulesBulkRoute = (router: SecuritySolutionPluginRouter) => { const config: Config = { validate: { body: buildRouteValidation( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts index f4aa51c6dcfc3..5eeaed6e9561f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts @@ -10,7 +10,7 @@ import { QueryRulesSchemaDecoded, } from '../../../../../common/detection_engine/schemas/request/query_rules_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { deleteRules } from '../../rules/delete_rules'; import { getIdError } from './utils'; @@ -20,7 +20,7 @@ import { deleteNotifications } from '../../notifications/delete_notifications'; import { deleteRuleActionsSavedObject } from '../../rule_actions/delete_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; -export const deleteRulesRoute = (router: IRouter) => { +export const deleteRulesRoute = (router: SecuritySolutionPluginRouter) => { router.delete( { path: DETECTION_ENGINE_RULES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts index 8df9f114559a8..9828747ca9523 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts @@ -11,7 +11,7 @@ import { ExportRulesSchemaDecoded, } from '../../../../../common/detection_engine/schemas/request/export_rules_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { ConfigType } from '../../../../config'; import { getNonPackagedRulesCount } from '../../rules/get_existing_prepackaged_rules'; @@ -19,7 +19,7 @@ import { getExportByObjectIds } from '../../rules/get_export_by_object_ids'; import { getExportAll } from '../../rules/get_export_all'; import { transformError, buildSiemResponse } from '../utils'; -export const exportRulesRoute = (router: IRouter, config: ConfigType) => { +export const exportRulesRoute = (router: SecuritySolutionPluginRouter, config: ConfigType) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_export`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts index b2074ad20b674..b32497f52d573 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts @@ -9,7 +9,7 @@ import { findRulesSchema, FindRulesSchemaDecoded, } from '../../../../../common/detection_engine/schemas/request/find_rules_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { findRules } from '../../rules/find_rules'; import { transformValidateFindAlerts } from './validate'; @@ -18,7 +18,7 @@ import { getRuleActionsSavedObject } from '../../rule_actions/get_rule_actions_s import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -export const findRulesRoute = (router: IRouter) => { +export const findRulesRoute = (router: SecuritySolutionPluginRouter) => { router.get( { path: `${DETECTION_ENGINE_RULES_URL}/_find`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts index 3ae228c165a56..add8e5435283f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts @@ -5,7 +5,7 @@ */ import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { RuleStatusResponse } from '../../rules/types'; import { transformError, buildSiemResponse, mergeStatuses, getFailingRules } from '../utils'; @@ -22,7 +22,7 @@ import { * @param router * @returns RuleStatusResponse */ -export const findRulesStatusesRoute = (router: IRouter) => { +export const findRulesStatusesRoute = (router: SecuritySolutionPluginRouter) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_find_statuses`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts index 4cd5238ccb1ef..45ed207b8bbe8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts @@ -9,7 +9,7 @@ import { PrePackagedRulesAndTimelinesStatusSchema, prePackagedRulesAndTimelinesStatusSchema, } from '../../../../../common/detection_engine/schemas/response/prepackaged_rules_status_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_PREPACKAGED_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { getPrepackagedRules } from '../../rules/get_prepackaged_rules'; @@ -24,7 +24,7 @@ import { checkTimelinesStatus } from '../../../timeline/routes/utils/check_timel import { checkTimelineStatusRt } from '../../../timeline/routes/schemas/check_timelines_status_schema'; export const getPrepackagedRulesStatusRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts index a033c16cd5e99..367ad866ae55f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts @@ -76,6 +76,7 @@ describe('import_rules_route', () => { it('returns 404 if siem client is unavailable', async () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; + // @ts-expect-error const response = await server.inject(request, contextWithoutSecuritySolution); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts index adf027a430f8a..b782ba1a071de 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts @@ -20,7 +20,7 @@ import { importRulesSchema as importRulesResponseSchema, } from '../../../../../common/detection_engine/schemas/response/import_rules_schema'; import { isMlRule } from '../../../../../common/machine_learning/helpers'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { ConfigType } from '../../../../config'; import { SetupPlugins } from '../../../../plugin'; @@ -49,7 +49,11 @@ type PromiseFromStreams = ImportRulesSchemaDecoded | Error; const CHUNK_PARSED_OBJECT_SIZE = 50; -export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupPlugins['ml']) => { +export const importRulesRoute = ( + router: SecuritySolutionPluginRouter, + config: ConfigType, + ml: SetupPlugins['ml'] +) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_import`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts index 7dfb4daa1a0a2..380b9f2ae2c3c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts @@ -12,7 +12,7 @@ import { } from '../../../../../common/detection_engine/schemas/request/patch_rules_bulk_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; @@ -26,7 +26,10 @@ import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_s import { readRules } from '../../rules/read_rules'; import { PartialFilter } from '../../types'; -export const patchRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => { +export const patchRulesBulkRoute = ( + router: SecuritySolutionPluginRouter, + ml: SetupPlugins['ml'] +) => { router.patch( { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_update`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts index aadb13ef54e72..66a873860189b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts @@ -11,7 +11,7 @@ import { PatchRulesSchemaDecoded, patchRulesSchema, } from '../../../../../common/detection_engine/schemas/request/patch_rules_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; @@ -25,7 +25,7 @@ import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_s import { readRules } from '../../rules/read_rules'; import { PartialFilter } from '../../types'; -export const patchRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { +export const patchRulesRoute = (router: SecuritySolutionPluginRouter, ml: SetupPlugins['ml']) => { router.patch( { path: DETECTION_ENGINE_RULES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts index 6fb82166d416b..a1f081ffb9e0e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts @@ -10,7 +10,7 @@ import { QueryRulesSchemaDecoded, } from '../../../../../common/detection_engine/schemas/request/query_rules_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { getIdError } from './utils'; import { transformValidate } from './validate'; @@ -19,7 +19,7 @@ import { readRules } from '../../rules/read_rules'; import { getRuleActionsSavedObject } from '../../rule_actions/get_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; -export const readRulesRoute = (router: IRouter) => { +export const readRulesRoute = (router: SecuritySolutionPluginRouter) => { router.get( { path: DETECTION_ENGINE_RULES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts index 72583a5a78709..3da78c2f9736d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts @@ -68,6 +68,7 @@ describe('update_rules_bulk', () => { it('returns 404 if siem client is unavailable', async () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; + // @ts-expect-error const response = await server.inject(getUpdateBulkRequest(), contextWithoutSecuritySolution); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts index 5f9789220bc10..dc5f7855cae29 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts @@ -9,7 +9,7 @@ import { updateRuleValidateTypeDependents } from '../../../../../common/detectio import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { updateRulesBulkSchema } from '../../../../../common/detection_engine/schemas/request/update_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; @@ -21,7 +21,10 @@ import { updateRules } from '../../rules/update_rules'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; -export const updateRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => { +export const updateRulesBulkRoute = ( + router: SecuritySolutionPluginRouter, + ml: SetupPlugins['ml'] +) => { router.put( { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_update`, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts index 96710b6f1d763..0c1500fecd6e4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts @@ -75,6 +75,7 @@ describe('update_rules', () => { it('returns 404 if siem client is unavailable', async () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; + // @ts-expect-error const response = await server.inject(getUpdateRequest(), contextWithoutSecuritySolution); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts index aa85747e3ce41..d3b3b23627a9e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts @@ -6,7 +6,7 @@ import { updateRulesSchema } from '../../../../../common/detection_engine/schemas/request'; import { updateRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/update_rules_type_dependents'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; @@ -19,7 +19,7 @@ import { updateRulesNotifications } from '../../rules/update_rules_notifications import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -export const updateRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { +export const updateRulesRoute = (router: SecuritySolutionPluginRouter, ml: SetupPlugins['ml']) => { router.put( { path: DETECTION_ENGINE_RULES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts index 313cc37b20d88..4d3394cb0b775 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { SetupPlugins } from '../../../../plugin'; import { DETECTION_ENGINE_SIGNALS_MIGRATION_URL } from '../../../../../common/constants'; import { createSignalsMigrationSchema } from '../../../../../common/detection_engine/schemas/request/create_signals_migration_schema'; @@ -20,7 +20,7 @@ import { getSignalVersionsByIndex } from '../../migrations/get_signal_versions_b import { SIGNALS_TEMPLATE_VERSION } from '../index/get_signals_template'; export const createSignalsMigrationRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, security: SetupPlugins['security'] ) => { router.post( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts index 2515a5fabe992..b1be5d5df6bfc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { SetupPlugins } from '../../../../plugin'; import { DETECTION_ENGINE_SIGNALS_MIGRATION_URL } from '../../../../../common/constants'; import { deleteSignalsMigrationSchema } from '../../../../../common/detection_engine/schemas/request/delete_signals_migration_schema'; @@ -14,7 +14,7 @@ import { signalsMigrationService } from '../../migrations/migration_service'; import { getMigrationSavedObjectsById } from '../../migrations/get_migration_saved_objects_by_id'; export const deleteSignalsMigrationRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, security: SetupPlugins['security'] ) => { router.delete( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts index 2c02c0768dadf..186116bdc97e6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { SetupPlugins } from '../../../../plugin'; import { DETECTION_ENGINE_SIGNALS_FINALIZE_MIGRATION_URL } from '../../../../../common/constants'; import { finalizeSignalsMigrationSchema } from '../../../../../common/detection_engine/schemas/request/finalize_signals_migration_schema'; @@ -16,7 +16,7 @@ import { buildSiemResponse, transformError } from '../utils'; import { getMigrationSavedObjectsById } from '../../migrations/get_migration_saved_objects_by_id'; export const finalizeSignalsMigrationRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, security: SetupPlugins['security'] ) => { router.post( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts index ed6546b0bf4f1..d36fa643964ab 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_SIGNALS_MIGRATION_STATUS_URL } from '../../../../../common/constants'; import { getSignalsMigrationStatusSchema } from '../../../../../common/detection_engine/schemas/request/get_signals_migration_status_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; @@ -17,7 +17,7 @@ import { isOutdated, signalsAreOutdated } from '../../migrations/helpers'; import { getTemplateVersion } from '../index/check_template_version'; import { buildSiemResponse, transformError } from '../utils'; -export const getSignalsMigrationStatusRoute = (router: IRouter) => { +export const getSignalsMigrationStatusRoute = (router: SecuritySolutionPluginRouter) => { router.get( { path: DETECTION_ENGINE_SIGNALS_MIGRATION_STATUS_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts index 97b63025a86eb..5db9c75b6371e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts @@ -44,6 +44,7 @@ describe('set signal status', () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; const response = await server.inject( getSetSignalStatusByQueryRequest(), + // @ts-expect-error contextWithoutSecuritySolution ); expect(response.status).toEqual(404); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts index be6e57aee6d0c..4201a0d1ebe57 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts @@ -9,12 +9,12 @@ import { SetSignalsStatusSchemaDecoded, setSignalsStatusSchema, } from '../../../../../common/detection_engine/schemas/request/set_signal_status_schema'; -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_SIGNALS_STATUS_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -export const setSignalsStatusRoute = (router: IRouter) => { +export const setSignalsStatusRoute = (router: SecuritySolutionPluginRouter) => { router.post( { path: DETECTION_ENGINE_SIGNALS_STATUS_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts index 3ab4775f890ac..d1010a80c5b98 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_QUERY_SIGNALS_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; @@ -14,7 +14,7 @@ import { QuerySignalsSchemaDecoded, } from '../../../../../common/detection_engine/schemas/request/query_signals_index_schema'; -export const querySignalsRoute = (router: IRouter) => { +export const querySignalsRoute = (router: SecuritySolutionPluginRouter) => { router.post( { path: DETECTION_ENGINE_QUERY_SIGNALS_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts index 9c508f99244cb..9be3a3b5f2f98 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_TAGS_URL } from '../../../../../common/constants'; import { transformError, buildSiemResponse } from '../utils'; import { readTags } from '../../tags/read_tags'; -export const readTagsRoute = (router: IRouter) => { +export const readTagsRoute = (router: SecuritySolutionPluginRouter) => { router.get( { path: DETECTION_ENGINE_TAGS_URL, diff --git a/x-pack/plugins/security_solution/server/lib/framework/kibana_framework_adapter.ts b/x-pack/plugins/security_solution/server/lib/framework/kibana_framework_adapter.ts index 8327af846d1ac..7aff8352d6336 100644 --- a/x-pack/plugins/security_solution/server/lib/framework/kibana_framework_adapter.ts +++ b/x-pack/plugins/security_solution/server/lib/framework/kibana_framework_adapter.ts @@ -7,16 +7,18 @@ import { GraphQLSchema } from 'graphql'; import { runHttpQuery } from 'apollo-server-core'; import { schema as configSchema } from '@kbn/config-schema'; -import { +import type { CoreSetup, - IRouter, KibanaResponseFactory, - RequestHandlerContext, KibanaRequest, } from '../../../../../../src/core/server'; import { IndexPatternsFetcher, UI_SETTINGS } from '../../../../../../src/plugins/data/server'; import { AuthenticatedUser } from '../../../../security/common/model'; import { SetupPlugins } from '../../plugin'; +import type { + SecuritySolutionRequestHandlerContext, + SecuritySolutionPluginRouter, +} from '../../types'; import { FrameworkAdapter, @@ -27,7 +29,7 @@ import { import { buildSiemResponse } from '../detection_engine/routes/utils'; export class KibanaBackendFrameworkAdapter implements FrameworkAdapter { - private router: IRouter; + private router: SecuritySolutionPluginRouter; private security: SetupPlugins['security']; constructor(core: CoreSetup, plugins: SetupPlugins) { @@ -125,7 +127,7 @@ export class KibanaBackendFrameworkAdapter implements FrameworkAdapter { export function wrapRequest( request: KibanaRequest, - context: RequestHandlerContext, + context: SecuritySolutionRequestHandlerContext, user: AuthenticatedUser | null ): FrameworkRequest { return { diff --git a/x-pack/plugins/security_solution/server/lib/framework/types.ts b/x-pack/plugins/security_solution/server/lib/framework/types.ts index 1f626d9fb2dc7..b1973e15ef95b 100644 --- a/x-pack/plugins/security_solution/server/lib/framework/types.ts +++ b/x-pack/plugins/security_solution/server/lib/framework/types.ts @@ -7,9 +7,10 @@ import { IndicesGetMappingParams } from 'elasticsearch'; import { GraphQLSchema } from 'graphql'; -import { RequestHandlerContext, KibanaRequest } from '../../../../../../src/core/server'; +import { KibanaRequest } from '../../../../../../src/core/server'; import { AuthenticatedUser } from '../../../../security/common/model'; import { ESQuery } from '../../../common/typed_json'; +import type { SecuritySolutionRequestHandlerContext } from '../../types'; import { PaginationInput, PaginationInputPaginated, @@ -45,7 +46,7 @@ export interface FrameworkAdapter { export interface FrameworkRequest extends Pick { [internalFrameworkRequest]: KibanaRequest; - context: RequestHandlerContext; + context: SecuritySolutionRequestHandlerContext; user: AuthenticatedUser | null; } diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts index 67fc3167a4a29..2a366576608a8 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts @@ -5,7 +5,7 @@ */ import uuid from 'uuid'; -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { ConfigType } from '../../..'; import { transformError, buildSiemResponse } from '../../detection_engine/routes/utils'; import { TIMELINE_DRAFT_URL } from '../../../../common/constants'; @@ -18,7 +18,7 @@ import { cleanDraftTimelineSchema } from './schemas/clean_draft_timelines_schema import { TimelineType } from '../../../../common/types/timeline'; export const cleanDraftTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/create_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/create_timelines_route.ts index 77cd49406baa1..7f9a32a2275dc 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/create_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/create_timelines_route.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { TIMELINE_URL } from '../../../../common/constants'; @@ -23,7 +23,7 @@ import { createTimelines } from './utils/create_timelines'; import { DEFAULT_ERROR } from './utils/failure_cases'; export const createTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/export_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/export_timelines_route.ts index 38ee51fb7aa0c..f24a9234dd8fa 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/export_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/export_timelines_route.ts @@ -5,7 +5,7 @@ */ import { TIMELINE_EXPORT_URL } from '../../../../common/constants'; -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { ConfigType } from '../../../config'; import { transformError, buildSiemResponse } from '../../detection_engine/routes/utils'; @@ -19,7 +19,7 @@ import { buildFrameworkRequest } from './utils/common'; import { SetupPlugins } from '../../../plugin'; export const exportTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts index 43129f0e15f0e..59179dd33f5a3 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { ConfigType } from '../../..'; import { transformError, buildSiemResponse } from '../../detection_engine/routes/utils'; import { TIMELINE_DRAFT_URL } from '../../../../common/constants'; @@ -16,7 +16,7 @@ import { draftTimelineDefaults } from '../default_timeline'; import { getDraftTimelineSchema } from './schemas/get_draft_timelines_schema'; export const getDraftTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_timeline_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_timeline_route.ts index e46a644d6820e..9496513ed4cc9 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_timeline_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_timeline_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { TIMELINE_URL } from '../../../../common/constants'; @@ -21,7 +21,7 @@ import { getAllTimeline } from '../saved_object'; import { TimelineStatus } from '../../../../common/types/timeline'; export const getTimelineRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.ts index 811d4531b86a7..5197677864248 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.ts @@ -7,7 +7,7 @@ import { extname } from 'path'; import { Readable } from 'stream'; -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { TIMELINE_IMPORT_URL } from '../../../../common/constants'; @@ -21,7 +21,7 @@ import { ImportTimelinesPayloadSchemaRt } from './schemas/import_timelines_schem import { buildFrameworkRequest } from './utils/common'; export const importTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/install_prepacked_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/install_prepacked_timelines_route.ts index aba05054abfe2..04608a821ca75 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/install_prepacked_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/install_prepacked_timelines_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { TIMELINE_PREPACKAGED_URL } from '../../../../common/constants'; @@ -22,7 +22,7 @@ import { checkTimelineStatusRt } from './schemas/check_timelines_status_schema'; import { buildFrameworkRequest } from './utils/common'; export const installPrepackedTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts index 6b8ceea80c31a..2c650db0d6908 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../../../src/core/server'; +import type { SecuritySolutionPluginRouter } from '../../../types'; import { TIMELINE_URL } from '../../../../common/constants'; @@ -20,7 +20,7 @@ import { createTimelines } from './utils/create_timelines'; import { CompareTimelinesStatus } from './utils/compare_timelines_status'; export const updateTimelinesRoute = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, security: SetupPlugins['security'] ) => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts index c230e36e4c896..b6cbe92123adf 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts @@ -9,13 +9,14 @@ import fs from 'fs'; import { Readable } from 'stream'; import { createListStream } from '@kbn/utils'; -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import { KibanaRequest } from 'src/core/server'; import { SetupPlugins } from '../../../../plugin'; +import type { SecuritySolutionRequestHandlerContext } from '../../../../types'; import { FrameworkRequest } from '../../../framework'; export const buildFrameworkRequest = async ( - context: RequestHandlerContext, + context: SecuritySolutionRequestHandlerContext, security: SetupPlugins['security'], request: KibanaRequest ): Promise => { @@ -25,7 +26,7 @@ export const buildFrameworkRequest = async ( return set( 'user', user, - set( + set( 'context.core.savedObjects.client', savedObjectsClient, request diff --git a/x-pack/plugins/security_solution/server/lib/types.ts b/x-pack/plugins/security_solution/server/lib/types.ts index 618710ebd5fc6..06ef82de5715d 100644 --- a/x-pack/plugins/security_solution/server/lib/types.ts +++ b/x-pack/plugins/security_solution/server/lib/types.ts @@ -5,8 +5,8 @@ */ import { AuthenticatedUser } from '../../../security/common/model'; -import { RequestHandlerContext } from '../../../../../src/core/server'; export { ConfigType as Configuration } from '../config'; +import type { SecuritySolutionRequestHandlerContext } from '../types'; import { FrameworkAdapter, FrameworkRequest } from './framework'; import { Hosts } from './hosts'; @@ -36,7 +36,7 @@ export interface AppBackendLibs extends AppDomainLibs { export interface SiemContext { req: FrameworkRequest; - context: RequestHandlerContext; + context: SecuritySolutionRequestHandlerContext; user: AuthenticatedUser | null; } diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index 020237ad497f7..4e1521cb0f8d1 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -64,7 +64,7 @@ import { EndpointAppContextService } from './endpoint/endpoint_app_context_servi import { EndpointAppContext } from './endpoint/types'; import { registerDownloadExceptionListRoute } from './endpoint/routes/artifacts'; import { initUsageCollectors } from './usage'; -import { AppRequestContext } from './types'; +import type { SecuritySolutionRequestHandlerContext } from './types'; import { registerTrustedAppsRoutes } from './endpoint/routes/trusted_apps'; import { securitySolutionSearchStrategyProvider } from './search_strategy/security_solution'; import { securitySolutionIndexFieldsProvider } from './search_strategy/index_fields'; @@ -168,10 +168,10 @@ export class Plugin implements IPlugin => Promise.resolve(config), }; - const router = core.http.createRouter(); - core.http.registerRouteHandlerContext( + const router = core.http.createRouter(); + core.http.registerRouteHandlerContext( APP_ID, - (context, request, response): AppRequestContext => ({ + (context, request, response) => ({ getAppClient: () => this.appClientFactory.create(request), }) ); diff --git a/x-pack/plugins/security_solution/server/routes/index.ts b/x-pack/plugins/security_solution/server/routes/index.ts index 0204869904397..b02e69ffe42a0 100644 --- a/x-pack/plugins/security_solution/server/routes/index.ts +++ b/x-pack/plugins/security_solution/server/routes/index.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from '../../../../../src/core/server'; +import { SecuritySolutionPluginRouter } from '../types'; import { createRulesRoute } from '../lib/detection_engine/routes/rules/create_rules_route'; import { createIndexRoute } from '../lib/detection_engine/routes/index/create_index_route'; @@ -44,7 +44,7 @@ import { installPrepackedTimelinesRoute } from '../lib/timeline/routes/install_p import { getTimelineRoute } from '../lib/timeline/routes/get_timeline_route'; export const initRoutes = ( - router: IRouter, + router: SecuritySolutionPluginRouter, config: ConfigType, usingEphemeralEncryptionKey: boolean, security: SetupPlugins['security'], diff --git a/x-pack/plugins/security_solution/server/types.ts b/x-pack/plugins/security_solution/server/types.ts index 740e16636f1e0..c601738d981ac 100644 --- a/x-pack/plugins/security_solution/server/types.ts +++ b/x-pack/plugins/security_solution/server/types.ts @@ -3,6 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { ListsApiRequestHandlerContext } from '../../lists/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; +import type { AlertingApiRequestHandlerContext } from '../../alerts/server'; import { AppClient } from './client'; @@ -12,8 +16,11 @@ export interface AppRequestContext { getAppClient: () => AppClient; } -declare module 'src/core/server' { - interface RequestHandlerContext { - securitySolution?: AppRequestContext; - } -} +export type SecuritySolutionRequestHandlerContext = RequestHandlerContext & { + securitySolution: AppRequestContext; + licensing: LicensingApiRequestHandlerContext; + alerting: AlertingApiRequestHandlerContext; + lists?: ListsApiRequestHandlerContext; +}; + +export type SecuritySolutionPluginRouter = IRouter; diff --git a/x-pack/plugins/snapshot_restore/server/plugin.ts b/x-pack/plugins/snapshot_restore/server/plugin.ts index 4e3d743f5372c..baf39b25af4c9 100644 --- a/x-pack/plugins/snapshot_restore/server/plugin.ts +++ b/x-pack/plugins/snapshot_restore/server/plugin.ts @@ -3,12 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -declare module 'kibana/server' { - interface RequestHandlerContext { - snapshotRestore?: SnapshotRestoreContext; - } -} - import { first } from 'rxjs/operators'; import { i18n } from '@kbn/i18n'; import { @@ -17,7 +11,6 @@ import { Plugin, Logger, PluginInitializerContext, - ILegacyScopedClusterClient, } from 'kibana/server'; import { PLUGIN, APP_REQUIRED_CLUSTER_PRIVILEGES } from '../common'; @@ -26,13 +19,9 @@ import { ApiRoutes } from './routes'; import { wrapEsError } from './lib'; import { isEsError } from './shared_imports'; import { elasticsearchJsPlugin } from './client/elasticsearch_sr'; -import { Dependencies } from './types'; +import type { Dependencies, SnapshotRestoreRequestHandlerContext } from './types'; import { SnapshotRestoreConfig } from './config'; -export interface SnapshotRestoreContext { - client: ILegacyScopedClusterClient; -} - async function getCustomEsClient(getStartServices: CoreSetup['getStartServices']) { const [core] = await getStartServices(); const esClientConfig = { plugins: [elasticsearchJsPlugin] }; @@ -65,7 +54,7 @@ export class SnapshotRestoreServerPlugin implements Plugin return; } - const router = http.createRouter(); + const router = http.createRouter(); this.license.setup( { @@ -95,13 +84,16 @@ export class SnapshotRestoreServerPlugin implements Plugin ], }); - http.registerRouteHandlerContext('snapshotRestore', async (ctx, request) => { - this.snapshotRestoreESClient = - this.snapshotRestoreESClient ?? (await getCustomEsClient(getStartServices)); - return { - client: this.snapshotRestoreESClient.asScoped(request), - }; - }); + http.registerRouteHandlerContext( + 'snapshotRestore', + async (ctx, request) => { + this.snapshotRestoreESClient = + this.snapshotRestoreESClient ?? (await getCustomEsClient(getStartServices)); + return { + client: this.snapshotRestoreESClient.asScoped(request), + }; + } + ); this.apiRoutes.setup({ router, diff --git a/x-pack/plugins/snapshot_restore/server/services/license.ts b/x-pack/plugins/snapshot_restore/server/services/license.ts index 9b68acd073c4a..4c1478340c30f 100644 --- a/x-pack/plugins/snapshot_restore/server/services/license.ts +++ b/x-pack/plugins/snapshot_restore/server/services/license.ts @@ -4,15 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import { Logger } from 'src/core/server'; -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from 'kibana/server'; +import type { KibanaRequest, KibanaResponseFactory, RequestHandler } from 'kibana/server'; import { LicensingPluginSetup } from '../../../licensing/server'; import { LicenseType } from '../../../licensing/common/types'; +import type { SnapshotRestoreRequestHandlerContext } from '../types'; export interface LicenseStatus { isValid: boolean; @@ -53,11 +49,13 @@ export class License { }); } - guardApiRoute(handler: RequestHandler) { + guardApiRoute( + handler: RequestHandler + ) { const license = this; return function licenseCheck( - ctx: RequestHandlerContext, + ctx: Context, request: KibanaRequest, response: KibanaResponseFactory ) { diff --git a/x-pack/plugins/snapshot_restore/server/types.ts b/x-pack/plugins/snapshot_restore/server/types.ts index eb51f086deacc..dcef4b54e31b5 100644 --- a/x-pack/plugins/snapshot_restore/server/types.ts +++ b/x-pack/plugins/snapshot_restore/server/types.ts @@ -3,7 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { LegacyScopedClusterClient, IRouter } from 'src/core/server'; +import type { + LegacyScopedClusterClient, + ILegacyScopedClusterClient, + IRouter, + RequestHandlerContext, +} from 'src/core/server'; import { LicensingPluginSetup } from '../../licensing/server'; import { SecurityPluginSetup } from '../../security/server'; import { CloudSetup } from '../../cloud/server'; @@ -20,7 +25,7 @@ export interface Dependencies { } export interface RouteDependencies { - router: IRouter; + router: SnapshotRestoreRouter; license: License; config: { isSlmEnabled: boolean; @@ -50,3 +55,22 @@ export interface ResolveIndexResponseFromES { } export type CallAsCurrentUser = LegacyScopedClusterClient['callAsCurrentUser']; + +/** + * @internal + */ +export interface SnapshotRestoreContext { + client: ILegacyScopedClusterClient; +} + +/** + * @internal + */ +export interface SnapshotRestoreRequestHandlerContext extends RequestHandlerContext { + snapshotRestore: SnapshotRestoreContext; +} + +/** + * @internal + */ +export type SnapshotRestoreRouter = IRouter; diff --git a/x-pack/plugins/spaces/server/plugin.ts b/x-pack/plugins/spaces/server/plugin.ts index e50ab60a27738..24bf96e81ce1a 100644 --- a/x-pack/plugins/spaces/server/plugin.ts +++ b/x-pack/plugins/spaces/server/plugin.ts @@ -36,6 +36,7 @@ import { SpacesClientService, SpacesClientWrapper, } from './spaces_client'; +import type { SpacesRequestHandlerContext } from './types'; export interface PluginsSetup { features: FeaturesPluginSetup; @@ -123,7 +124,7 @@ export class Plugin { logger: this.log, }); - const externalRouter = core.http.createRouter(); + const externalRouter = core.http.createRouter(); initExternalSpacesApi({ externalRouter, log: this.log, @@ -132,7 +133,7 @@ export class Plugin { usageStatsServicePromise, }); - const internalRouter = core.http.createRouter(); + const internalRouter = core.http.createRouter(); initInternalSpacesApi({ internalRouter, getSpacesService, diff --git a/x-pack/plugins/spaces/server/routes/api/external/index.ts b/x-pack/plugins/spaces/server/routes/api/external/index.ts index d481c2e0675fa..6ece39f621801 100644 --- a/x-pack/plugins/spaces/server/routes/api/external/index.ts +++ b/x-pack/plugins/spaces/server/routes/api/external/index.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Logger, IRouter, CoreSetup } from 'src/core/server'; +import { Logger, CoreSetup } from 'src/core/server'; import { initDeleteSpacesApi } from './delete'; import { initGetSpaceApi } from './get'; import { initGetAllSpacesApi } from './get_all'; @@ -14,9 +14,10 @@ import { SpacesServiceStart } from '../../../spaces_service'; import { UsageStatsServiceSetup } from '../../../usage_stats'; import { initCopyToSpacesApi } from './copy_to_space'; import { initShareToSpacesApi } from './share_to_space'; +import type { SpacesRouter } from '../../../types'; export interface ExternalRouteDeps { - externalRouter: IRouter; + externalRouter: SpacesRouter; getStartServices: CoreSetup['getStartServices']; getSpacesService: () => SpacesServiceStart; usageStatsServicePromise: Promise; diff --git a/x-pack/plugins/spaces/server/routes/api/internal/index.ts b/x-pack/plugins/spaces/server/routes/api/internal/index.ts index 675cdb548543d..574b7a25f2d10 100644 --- a/x-pack/plugins/spaces/server/routes/api/internal/index.ts +++ b/x-pack/plugins/spaces/server/routes/api/internal/index.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'src/core/server'; +import type { SpacesRouter } from '../../../types'; import { SpacesServiceStart } from '../../../spaces_service/spaces_service'; import { initGetActiveSpaceApi } from './get_active_space'; export interface InternalRouteDeps { - internalRouter: IRouter; + internalRouter: SpacesRouter; getSpacesService: () => SpacesServiceStart; } diff --git a/x-pack/plugins/spaces/server/routes/lib/licensed_route_handler.ts b/x-pack/plugins/spaces/server/routes/lib/licensed_route_handler.ts index d56414a12b838..d507802011dc9 100644 --- a/x-pack/plugins/spaces/server/routes/lib/licensed_route_handler.ts +++ b/x-pack/plugins/spaces/server/routes/lib/licensed_route_handler.ts @@ -4,10 +4,22 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandler } from 'kibana/server'; +import type { RequestHandler, RequestHandlerContext } from 'kibana/server'; +import type { LicensingApiRequestHandlerContext } from '../../../../licensing/server'; -export const createLicensedRouteHandler = (handler: RequestHandler) => { - const licensedRouteHandler: RequestHandler = (context, request, responseToolkit) => { +export const createLicensedRouteHandler = < + P, + Q, + B, + Context extends RequestHandlerContext & { licensing: LicensingApiRequestHandlerContext } +>( + handler: RequestHandler +) => { + const licensedRouteHandler: RequestHandler = ( + context, + request, + responseToolkit + ) => { const { license } = context.licensing; const licenseCheck = license.check('spaces', 'basic'); if (licenseCheck.state === 'unavailable' || licenseCheck.state === 'invalid') { diff --git a/x-pack/plugins/spaces/server/types.ts b/x-pack/plugins/spaces/server/types.ts new file mode 100644 index 0000000000000..c43a589ed5775 --- /dev/null +++ b/x-pack/plugins/spaces/server/types.ts @@ -0,0 +1,20 @@ +/* + * 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 type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; + +/** + * @internal + */ +export interface SpacesRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; +} + +/** + * @internal + */ +export type SpacesRouter = IRouter; diff --git a/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts index 92965515f0876..6e949012e7ed1 100644 --- a/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts @@ -5,8 +5,7 @@ */ import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { - IRouter, +import type { SavedObjectsClientContract, ISavedObjectsRepository, IScopedClusterClient, @@ -15,6 +14,7 @@ import { UMKibanaRoute } from '../../../rest_api'; import { PluginSetupContract } from '../../../../../features/server'; import { MlPluginSetup as MlSetup } from '../../../../../ml/server'; import { UptimeESClient } from '../../lib'; +import type { UptimeRouter } from '../../../types'; export type UMElasticsearchQueryFn = ( params: { @@ -29,7 +29,7 @@ export type UMSavedObjectsQueryFn = ( ) => Promise | T; export interface UptimeCoreSetup { - router: IRouter; + router: UptimeRouter; } export interface UptimeCorePlugins { diff --git a/x-pack/plugins/uptime/server/lib/alerts/status_check.test.ts b/x-pack/plugins/uptime/server/lib/alerts/status_check.test.ts index ed831f4e17368..3a6516bd33d41 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/status_check.test.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/status_check.test.ts @@ -18,7 +18,6 @@ import { AlertInstanceState, AlertInstanceContext, } from '../../../../alerts/server'; -import { IRouter } from 'kibana/server'; import { UMServerLibs } from '../lib'; import { UptimeCorePlugins, UptimeCoreSetup } from '../adapters'; import { DYNAMIC_SETTINGS_DEFAULTS } from '../../../common/constants'; @@ -26,6 +25,7 @@ import { alertsMock, AlertServicesMock } from '../../../../alerts/server/mocks'; import { GetMonitorStatusResult } from '../requests/get_monitor_status'; import { makePing } from '../../../common/runtime_types/ping'; import { GetMonitorAvailabilityResult } from '../requests/get_monitor_availability'; +import type { UptimeRouter } from '../../types'; /** * The alert takes some dependencies as parameters; these are things like @@ -35,7 +35,7 @@ import { GetMonitorAvailabilityResult } from '../requests/get_monitor_availabili * so we don't have to mock them all for each test. */ const bootstrapDependencies = (customRequests?: any) => { - const router: IRouter = {} as IRouter; + const router = {} as UptimeRouter; // these server/libs parameters don't have any functionality, which is fine // because we aren't testing them here const server: UptimeCoreSetup = { router }; diff --git a/x-pack/plugins/uptime/server/rest_api/types.ts b/x-pack/plugins/uptime/server/rest_api/types.ts index 4e627cebb3459..3d3f2393d242f 100644 --- a/x-pack/plugins/uptime/server/rest_api/types.ts +++ b/x-pack/plugins/uptime/server/rest_api/types.ts @@ -10,12 +10,12 @@ import { RouteConfig, RouteMethod, SavedObjectsClientContract, - RequestHandlerContext, KibanaRequest, KibanaResponseFactory, IKibanaResponse, } from 'kibana/server'; import { UMServerLibs, UptimeESClient } from '../lib/lib'; +import type { UptimeRequestHandlerContext } from '../types'; /** * Defines the basic properties employed by Uptime routes. @@ -38,7 +38,9 @@ export type UMRouteDefinition = UMServerRoute & * provided by the Kibana platform. Route objects must conform to this type in order * to successfully interact with the Kibana platform. */ -export type UMKibanaRoute = UMRouteDefinition>; +export type UMKibanaRoute = UMRouteDefinition< + RequestHandler +>; /** * This is an abstraction over the default Kibana route type. This allows us to use custom @@ -68,7 +70,7 @@ export type UMRouteHandler = ({ savedObjectsClient, }: { uptimeEsClient: UptimeESClient; - context: RequestHandlerContext; + context: UptimeRequestHandlerContext; request: KibanaRequest, Record, Record>; response: KibanaResponseFactory; savedObjectsClient: SavedObjectsClientContract; diff --git a/x-pack/plugins/uptime/server/types.ts b/x-pack/plugins/uptime/server/types.ts new file mode 100644 index 0000000000000..7a107268b2cfd --- /dev/null +++ b/x-pack/plugins/uptime/server/types.ts @@ -0,0 +1,21 @@ +/* + * 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 type { IRouter, RequestHandlerContext } from 'src/core/server'; +import type { AlertingApiRequestHandlerContext } from '../../alerts/server'; +import type { LicensingApiRequestHandlerContext } from '../../licensing/server'; +/** + * @internal + */ +export interface UptimeRequestHandlerContext extends RequestHandlerContext { + licensing: LicensingApiRequestHandlerContext; + alerting: AlertingApiRequestHandlerContext; +} + +/** + * @internal + */ +export type UptimeRouter = IRouter; diff --git a/x-pack/plugins/watcher/server/index.ts b/x-pack/plugins/watcher/server/index.ts index 356be781fb194..51eb7bfa543fe 100644 --- a/x-pack/plugins/watcher/server/index.ts +++ b/x-pack/plugins/watcher/server/index.ts @@ -6,6 +6,4 @@ import { PluginInitializerContext } from 'kibana/server'; import { WatcherServerPlugin } from './plugin'; -export { WatcherContext } from './plugin'; - export const plugin = (ctx: PluginInitializerContext) => new WatcherServerPlugin(ctx); diff --git a/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts index 1b2476fc78b45..0d162f300d371 100644 --- a/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts +++ b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts @@ -4,20 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from 'kibana/server'; -import { RouteDependencies } from '../../types'; +import type { KibanaRequest, KibanaResponseFactory, RequestHandler } from 'kibana/server'; +import type { RouteDependencies, WatcherRequestHandlerContext } from '../../types'; -export const licensePreRoutingFactory = ( +export const licensePreRoutingFactory = ( { getLicenseStatus }: RouteDependencies, - handler: RequestHandler + handler: RequestHandler ) => { return function licenseCheck( - ctx: RequestHandlerContext, + ctx: Context, request: KibanaRequest, response: KibanaResponseFactory ) { diff --git a/x-pack/plugins/watcher/server/plugin.ts b/x-pack/plugins/watcher/server/plugin.ts index 9ff46283a72a6..8ce63ab009779 100644 --- a/x-pack/plugins/watcher/server/plugin.ts +++ b/x-pack/plugins/watcher/server/plugin.ts @@ -3,23 +3,20 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - -declare module 'kibana/server' { - interface RequestHandlerContext { - watcher?: WatcherContext; - } -} - import { CoreSetup, ILegacyCustomClusterClient, - ILegacyScopedClusterClient, Logger, Plugin, PluginInitializerContext, } from 'kibana/server'; import { PLUGIN, INDEX_NAMES } from '../common/constants'; -import { Dependencies, LicenseStatus, RouteDependencies } from './types'; +import type { + Dependencies, + LicenseStatus, + RouteDependencies, + WatcherRequestHandlerContext, +} from './types'; import { registerSettingsRoutes } from './routes/api/settings'; import { registerIndicesRoutes } from './routes/api/indices'; @@ -30,10 +27,6 @@ import { registerListFieldsRoute } from './routes/api/register_list_fields_route import { registerLoadHistoryRoute } from './routes/api/register_load_history_route'; import { elasticsearchJsPlugin } from './lib/elasticsearch_js_plugin'; -export interface WatcherContext { - client: ILegacyScopedClusterClient; -} - async function getCustomEsClient(getStartServices: CoreSetup['getStartServices']) { const [core] = await getStartServices(); const esConfig = { plugins: [elasticsearchJsPlugin] }; @@ -53,7 +46,7 @@ export class WatcherServerPlugin implements Plugin { } async setup({ http, getStartServices }: CoreSetup, { licensing, features }: Dependencies) { - const router = http.createRouter(); + const router = http.createRouter(); const routeDependencies: RouteDependencies = { router, getLicenseStatus: () => this.licenseStatus, @@ -85,12 +78,15 @@ export class WatcherServerPlugin implements Plugin { ], }); - http.registerRouteHandlerContext('watcher', async (ctx, request) => { - this.watcherESClient = this.watcherESClient ?? (await getCustomEsClient(getStartServices)); - return { - client: this.watcherESClient.asScoped(request), - }; - }); + http.registerRouteHandlerContext( + 'watcher', + async (ctx, request) => { + this.watcherESClient = this.watcherESClient ?? (await getCustomEsClient(getStartServices)); + return { + client: this.watcherESClient.asScoped(request), + }; + } + ); registerListFieldsRoute(routeDependencies); registerLoadHistoryRoute(routeDependencies); diff --git a/x-pack/plugins/watcher/server/types.ts b/x-pack/plugins/watcher/server/types.ts index 5ef3aef7de1c6..db31e94bf77ed 100644 --- a/x-pack/plugins/watcher/server/types.ts +++ b/x-pack/plugins/watcher/server/types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter } from 'kibana/server'; +import type { ILegacyScopedClusterClient, IRouter, RequestHandlerContext } from 'src/core/server'; import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; import { LicensingPluginSetup } from '../../licensing/server'; @@ -21,7 +21,7 @@ export interface ServerShim { } export interface RouteDependencies { - router: IRouter; + router: WatcherRouter; getLicenseStatus: () => LicenseStatus; } @@ -29,3 +29,22 @@ export interface LicenseStatus { hasRequired: boolean; message?: string; } + +/** + * @internal + */ +export interface WatcherContext { + client: ILegacyScopedClusterClient; +} + +/** + * @internal + */ +export interface WatcherRequestHandlerContext extends RequestHandlerContext { + watcher: WatcherContext; +} + +/** + * @internal + */ +export type WatcherRouter = IRouter;