Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unify response interface in handler and request interceptors #42442

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -8,5 +8,5 @@
<b>Signature:</b>

```typescript
export declare type AuthenticationHandler = (request: KibanaRequest, t: AuthToolkit) => AuthResult | Promise<AuthResult>;
export declare type AuthenticationHandler = (request: KibanaRequest, response: LifecycleResponseFactory, t: AuthToolkit) => AuthResult | KibanaResponse | Promise<AuthResult | KibanaResponse>;
```
Expand Up @@ -17,6 +17,4 @@ export interface AuthToolkit
| Property | Type | Description |
| --- | --- | --- |
| [authenticated](./kibana-plugin-server.authtoolkit.authenticated.md) | <code>(data?: AuthResultParams) =&gt; AuthResult</code> | Authentication is successful with given credentials, allow request to pass through |
| [redirected](./kibana-plugin-server.authtoolkit.redirected.md) | <code>(url: string) =&gt; AuthResult</code> | Authentication requires to interrupt request handling and redirect to a configured url |
| [rejected](./kibana-plugin-server.authtoolkit.rejected.md) | <code>(error: Error, options?: {</code><br/><code> statusCode?: number;</code><br/><code> }) =&gt; AuthResult</code> | Authentication is unsuccessful, fail the request with specified error. |

This file was deleted.

This file was deleted.

@@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-server](./kibana-plugin-server.md) &gt; [LifecycleResponseFactory](./kibana-plugin-server.lifecycleresponsefactory.md)

## LifecycleResponseFactory type

Creates an object containing redirection or error response with error details, HTTP headers, and other data transmitted to the client.

<b>Signature:</b>

```typescript
export declare type LifecycleResponseFactory = typeof lifecycleResponseFactory;
```
2 changes: 2 additions & 0 deletions docs/development/core/server/kibana-plugin-server.md
Expand Up @@ -81,12 +81,14 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [GetAuthHeaders](./kibana-plugin-server.getauthheaders.md) | Get headers to authenticate a user against Elasticsearch. |
| [Headers](./kibana-plugin-server.headers.md) | |
| [LegacyRequest](./kibana-plugin-server.legacyrequest.md) | Support Legacy platform request for the period of migration. |
| [LifecycleResponseFactory](./kibana-plugin-server.lifecycleresponsefactory.md) | Creates an object containing redirection or error response with error details, HTTP headers, and other data transmitted to the client. |
| [OnPostAuthHandler](./kibana-plugin-server.onpostauthhandler.md) | |
| [OnPreAuthHandler](./kibana-plugin-server.onpreauthhandler.md) | |
| [PluginInitializer](./kibana-plugin-server.plugininitializer.md) | The <code>plugin</code> export at the root of a plugin's <code>server</code> directory should conform to this interface. |
| [PluginName](./kibana-plugin-server.pluginname.md) | Dedicated type for plugin name/id that is supposed to make Map/Set/Arrays that use it as a key or value more obvious. |
| [RecursiveReadonly](./kibana-plugin-server.recursivereadonly.md) | |
| [ResponseError](./kibana-plugin-server.responseerror.md) | Error message and optional data send to the client in case of error. |
| [ResponseFactory](./kibana-plugin-server.responsefactory.md) | Creates an object containing request response payload, HTTP headers, error details, and other data transmitted to the client. |
| [RouteMethod](./kibana-plugin-server.routemethod.md) | The set of common HTTP methods supported by Kibana routing. |
| [SavedObjectsClientContract](./kibana-plugin-server.savedobjectsclientcontract.md) | \#\# SavedObjectsClient errors<!-- -->Since the SavedObjectsClient has its hands in everything we are a little paranoid about the way we present errors back to to application code. Ideally, all errors will be either:<!-- -->1. Caused by bad implementation (ie. undefined is not a function) and as such unpredictable 2. An error that has been classified and decorated appropriately by the decorators in [SavedObjectsErrorHelpers](./kibana-plugin-server.savedobjectserrorhelpers.md)<!-- -->Type 1 errors are inevitable, but since all expected/handle-able errors should be Type 2 the <code>isXYZError()</code> helpers exposed at <code>SavedObjectsErrorHelpers</code> should be used to understand and manage error responses from the <code>SavedObjectsClient</code>.<!-- -->Type 2 errors are decorated versions of the source error, so if the elasticsearch client threw an error it will be decorated based on its type. That means that rather than looking for <code>error.body.error.type</code> or doing substring checks on <code>error.body.error.reason</code>, just use the helpers to understand the meaning of the error:<!-- -->\`\`\`<!-- -->js if (SavedObjectsErrorHelpers.isNotFoundError(error)) { // handle 404 }<!-- -->if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) { // 401 handling should be automatic, but in case you wanted to know }<!-- -->// always rethrow the error unless you handle it throw error; \`\`\`<!-- -->\#\#\# 404s from missing index<!-- -->From the perspective of application code and APIs the SavedObjectsClient is a black box that persists objects. One of the internal details that users have no control over is that we use an elasticsearch index for persistance and that index might be missing.<!-- -->At the time of writing we are in the process of transitioning away from the operating assumption that the SavedObjects index is always available. Part of this transition is handling errors resulting from an index missing. These used to trigger a 500 error in most cases, and in others cause 404s with different error messages.<!-- -->From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The object the request/call was targeting could not be found. This is why \#14141 takes special care to ensure that 404 errors are generic and don't distinguish between index missing or document missing.<!-- -->\#\#\# 503s from missing index<!-- -->Unlike all other methods, create requests are supposed to succeed even when the Kibana index does not exist because it will be automatically created by elasticsearch. When that is not the case it is because Elasticsearch's <code>action.auto_create_index</code> setting prevents it from being created automatically so we throw a special 503 with the intention of informing the user that their Elasticsearch settings need to be updated.<!-- -->See [SavedObjectsErrorHelpers](./kibana-plugin-server.savedobjectserrorhelpers.md) |
| [SavedObjectsClientWrapperFactory](./kibana-plugin-server.savedobjectsclientwrapperfactory.md) | |
Expand Down
Expand Up @@ -8,5 +8,5 @@
<b>Signature:</b>

```typescript
export declare type OnPostAuthHandler<Params = any, Query = any, Body = any> = (request: KibanaRequest<Params, Query, Body>, t: OnPostAuthToolkit) => OnPostAuthResult | Promise<OnPostAuthResult>;
export declare type OnPostAuthHandler = (request: KibanaRequest, response: LifecycleResponseFactory, toolkit: OnPostAuthToolkit) => OnPostAuthResult | KibanaResponse | Promise<OnPostAuthResult | KibanaResponse>;
```
Expand Up @@ -17,6 +17,4 @@ export interface OnPostAuthToolkit
| Property | Type | Description |
| --- | --- | --- |
| [next](./kibana-plugin-server.onpostauthtoolkit.next.md) | <code>() =&gt; OnPostAuthResult</code> | To pass request to the next handler |
| [redirected](./kibana-plugin-server.onpostauthtoolkit.redirected.md) | <code>(url: string) =&gt; OnPostAuthResult</code> | To interrupt request handling and redirect to a configured url |
| [rejected](./kibana-plugin-server.onpostauthtoolkit.rejected.md) | <code>(error: Error, options?: {</code><br/><code> statusCode?: number;</code><br/><code> }) =&gt; OnPostAuthResult</code> | Fail the request with specified error. |

This file was deleted.

This file was deleted.

Expand Up @@ -8,5 +8,5 @@
<b>Signature:</b>

```typescript
export declare type OnPreAuthHandler<Params = any, Query = any, Body = any> = (request: KibanaRequest<Params, Query, Body>, t: OnPreAuthToolkit) => OnPreAuthResult | Promise<OnPreAuthResult>;
export declare type OnPreAuthHandler = (request: KibanaRequest, response: LifecycleResponseFactory, toolkit: OnPreAuthToolkit) => OnPreAuthResult | KibanaResponse | Promise<OnPreAuthResult | KibanaResponse>;
```
Expand Up @@ -17,6 +17,5 @@ export interface OnPreAuthToolkit
| Property | Type | Description |
| --- | --- | --- |
| [next](./kibana-plugin-server.onpreauthtoolkit.next.md) | <code>() =&gt; OnPreAuthResult</code> | To pass request to the next handler |
| [redirected](./kibana-plugin-server.onpreauthtoolkit.redirected.md) | <code>(url: string, options?: {</code><br/><code> forward: boolean;</code><br/><code> }) =&gt; OnPreAuthResult</code> | To interrupt request handling and redirect to a configured url. If "options.forwarded" = true, request will be forwarded to another url right on the server. |
| [rejected](./kibana-plugin-server.onpreauthtoolkit.rejected.md) | <code>(error: Error, options?: {</code><br/><code> statusCode?: number;</code><br/><code> }) =&gt; OnPreAuthResult</code> | Fail the request with specified error. |
| [rewriteUrl](./kibana-plugin-server.onpreauthtoolkit.rewriteurl.md) | <code>(url: string) =&gt; OnPreAuthResult</code> | Rewrite requested resources url before is was authenticated and routed to a handler |

This file was deleted.

This file was deleted.

@@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-server](./kibana-plugin-server.md) &gt; [OnPreAuthToolkit](./kibana-plugin-server.onpreauthtoolkit.md) &gt; [rewriteUrl](./kibana-plugin-server.onpreauthtoolkit.rewriteurl.md)

## OnPreAuthToolkit.rewriteUrl property

Rewrite requested resources url before is was authenticated and routed to a handler

<b>Signature:</b>

```typescript
rewriteUrl: (url: string) => OnPreAuthResult;
```
@@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-server](./kibana-plugin-server.md) &gt; [ResponseFactory](./kibana-plugin-server.responsefactory.md)

## ResponseFactory type

Creates an object containing request response payload, HTTP headers, error details, and other data transmitted to the client.

<b>Signature:</b>

```typescript
export declare type ResponseFactory = typeof responseFactory;
```
Expand Up @@ -22,7 +22,6 @@ export declare class Router
| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [path](./kibana-plugin-server.router.path.md) | | <code>string</code> | |
| [routes](./kibana-plugin-server.router.routes.md) | | <code>Array&lt;Readonly&lt;RouterRoute&gt;&gt;</code> | |

## Methods

Expand Down
11 changes: 0 additions & 11 deletions docs/development/core/server/kibana-plugin-server.router.routes.md

This file was deleted.

33 changes: 27 additions & 6 deletions src/core/server/http/http_server.mocks.ts
Expand Up @@ -16,14 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
import { Request, ResponseToolkit } from 'hapi';
import { Request } from 'hapi';
import { merge } from 'lodash';

import querystring from 'querystring';

import { schema } from '@kbn/config-schema';

import { KibanaRequest, RouteMethod } from './router';
import { KibanaRequest, LifecycleResponseFactory, RouteMethod, ResponseFactory } from './router';

interface RequestFixtureOptions {
headers?: Record<string, string>;
Expand Down Expand Up @@ -97,12 +97,33 @@ function createRawRequestMock(customization: DeepPartial<Request> = {}) {
) as Request;
}

function createRawResponseToolkitMock(customization: DeepPartial<ResponseToolkit> = {}) {
return merge({}, customization) as ResponseToolkit;
}
const createResponseFactoryMock = (): jest.Mocked<ResponseFactory> => ({
ok: jest.fn(),
accepted: jest.fn(),
noContent: jest.fn(),
custom: jest.fn(),
redirected: jest.fn(),
badRequest: jest.fn(),
unauthorized: jest.fn(),
forbidden: jest.fn(),
notFound: jest.fn(),
conflict: jest.fn(),
internalError: jest.fn(),
});

const createLifecycleResponseFactoryMock = (): jest.Mocked<LifecycleResponseFactory> => ({
redirected: jest.fn(),
badRequest: jest.fn(),
unauthorized: jest.fn(),
forbidden: jest.fn(),
notFound: jest.fn(),
conflict: jest.fn(),
internalError: jest.fn(),
});

export const httpServerMock = {
createKibanaRequest: createKibanaRequestMock,
createRawRequest: createRawRequestMock,
createRawResponseToolkit: createRawResponseToolkitMock,
createResponseFactory: createResponseFactoryMock,
createLifecycleResponseFactory: createLifecycleResponseFactoryMock,
};