-
Notifications
You must be signed in to change notification settings - Fork 882
/
router.ts
401 lines (364 loc) · 13 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Any modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Request, ResponseObject, ResponseToolkit } from '@hapi/hapi';
import Boom from '@hapi/boom';
import { isConfigSchema } from '@osd/config-schema';
import { Logger } from '../../logging';
import { LegacyOpenSearchErrorHelpers } from '../../opensearch/legacy/errors';
import {
isUnauthorizedError as isOpenSearchUnauthorizedError,
UnauthorizedError as OpenSearchNotAuthorizedError,
} from '../../opensearch/client/errors';
import { OpenSearchDashboardsRequest } from './request';
import {
OpenSearchDashboardsResponseFactory,
opensearchDashboardsResponseFactory,
IOpenSearchDashboardsResponse,
ErrorHttpResponseOptions,
} from './response';
import { RouteConfig, RouteConfigOptions, RouteMethod, validBodyOutput } from './route';
import { HapiResponseAdapter } from './response_adapter';
import { RequestHandlerContext } from '../../../server';
import { wrapErrors } from './error_wrapper';
import { RouteValidator } from './validator';
interface RouterRoute {
method: RouteMethod;
path: string;
options: RouteConfigOptions<RouteMethod>;
handler: (
req: Request,
responseToolkit: ResponseToolkit
) => Promise<ResponseObject | Boom.Boom<any>>;
}
/**
* Route handler common definition
*
* @public
*/
export type RouteRegistrar<Method extends RouteMethod> = <P, Q, B>(
route: RouteConfig<P, Q, B, Method>,
handler: RequestHandler<P, Q, B, Method>
) => void;
/**
* Registers route handlers for specified resource path and method.
* See {@link RouteConfig} and {@link RequestHandler} for more information about arguments to route registrations.
*
* @public
*/
export interface IRouter {
/**
* Resulted path
*/
routerPath: string;
/**
* Register a route handler for `GET` request.
* @param route {@link RouteConfig} - a route configuration.
* @param handler {@link RequestHandler} - a function to call to respond to an incoming request
*/
get: RouteRegistrar<'get'>;
/**
* 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'>;
/**
* 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'>;
/**
* 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'>;
/**
* 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'>;
/**
* Wrap a router handler to catch and converts legacy boom errors to proper custom errors.
* @param handler {@link RequestHandler} - a route handler to wrap
*/
handleLegacyErrors: RequestHandlerWrapper;
/**
* Returns all routes registered with this router.
* @returns List of registered routes.
* @internal
*/
getRoutes: () => RouterRoute[];
}
export type ContextEnhancer<P, Q, B, Method extends RouteMethod> = (
handler: RequestHandler<P, Q, B, Method>
) => RequestHandlerEnhanced<P, Q, B, Method>;
function getRouteFullPath(routerPath: string, routePath: string) {
// If router's path ends with slash and route's path starts with slash,
// we should omit one of them to have a valid concatenated path.
const routePathStartIndex = routerPath.endsWith('/') && routePath.startsWith('/') ? 1 : 0;
return `${routerPath}${routePath.slice(routePathStartIndex)}`;
}
/**
* Create the validation schemas for a route
*
* @returns Route schemas if `validate` is specified on the route, otherwise
* undefined.
*/
function routeSchemasFromRouteConfig<P, Q, B>(
route: RouteConfig<P, Q, B, typeof routeMethod>,
routeMethod: RouteMethod
) {
// The type doesn't allow `validate` to be undefined, but it can still
// happen when it's used from JavaScript.
if (route.validate === undefined) {
throw new Error(
`The [${routeMethod}] at [${route.path}] does not have a 'validate' specified. Use 'false' as the value if you want to bypass validation.`
);
}
if (route.validate !== false) {
Object.entries(route.validate).forEach(([key, schema]) => {
if (!(isConfigSchema(schema) || typeof schema === 'function')) {
throw new Error(
`Expected a valid validation logic declared with '@osd/config-schema' package or a RouteValidationFunction at key: [${key}].`
);
}
});
}
if (route.validate) {
return RouteValidator.from(route.validate);
}
}
/**
* Create a valid options object with "sensible" defaults + adding some validation to the options fields
*
* @param method HTTP verb for these options
* @param routeConfig The route config definition
*/
function validOptions(
method: RouteMethod,
routeConfig: RouteConfig<unknown, unknown, unknown, typeof method>
) {
const shouldNotHavePayload = ['head', 'get'].includes(method);
const { options = {}, validate } = routeConfig;
const shouldValidateBody = (validate && !!validate.body) || !!options.body;
const { output } = options.body || {};
if (typeof output === 'string' && !validBodyOutput.includes(output)) {
throw new Error(
`[options.body.output: '${output}'] in route ${method.toUpperCase()} ${
routeConfig.path
} is not valid. Only '${validBodyOutput.join("' or '")}' are valid.`
);
}
const body = shouldNotHavePayload
? undefined
: {
// If it's not a GET (requires payload) but no body validation is required (or no body options are specified),
// We assume the route does not care about the body => use the memory-cheapest approach (stream and no parsing)
output: !shouldValidateBody ? ('stream' as const) : undefined,
parse: !shouldValidateBody ? false : undefined,
// User's settings should overwrite any of the "desired" values
...options.body,
};
return { ...options, body };
}
/**
* @internal
*/
export class Router implements IRouter {
public routes: Array<Readonly<RouterRoute>> = [];
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<any, any, any, any>
) {
const buildMethod = <Method extends RouteMethod>(method: Method) => <P, Q, B>(
route: RouteConfig<P, Q, B, Method>,
handler: RequestHandler<P, Q, B, Method>
) => {
const routeSchemas = routeSchemasFromRouteConfig(route, method);
this.routes.push({
handler: async (req, responseToolkit) =>
await this.handle({
routeSchemas,
request: req,
responseToolkit,
handler: this.enhanceWithContext(handler),
}),
method,
path: getRouteFullPath(this.routerPath, route.path),
options: validOptions(method, route),
});
};
this.get = buildMethod('get');
this.post = buildMethod('post');
this.delete = buildMethod('delete');
this.put = buildMethod('put');
this.patch = buildMethod('patch');
}
public getRoutes() {
return [...this.routes];
}
public handleLegacyErrors = wrapErrors;
private async handle<P, Q, B>({
routeSchemas,
request,
responseToolkit,
handler,
}: {
request: Request;
responseToolkit: ResponseToolkit;
handler: RequestHandlerEnhanced<P, Q, B, typeof request.method>;
routeSchemas?: RouteValidator<P, Q, B>;
}) {
let opensearchDashboardsRequest: OpenSearchDashboardsRequest<P, Q, B, typeof request.method>;
const hapiResponseAdapter = new HapiResponseAdapter(responseToolkit);
try {
opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request, routeSchemas);
} catch (e) {
return hapiResponseAdapter.toBadRequest(e.message);
}
try {
const opensearchDashboardsResponse = await handler(
opensearchDashboardsRequest,
opensearchDashboardsResponseFactory
);
return hapiResponseAdapter.handle(opensearchDashboardsResponse);
} catch (e) {
this.log.error(e);
// forward 401 errors from OpenSearch client
if (isOpenSearchUnauthorizedError(e)) {
return hapiResponseAdapter.handle(
opensearchDashboardsResponseFactory.unauthorized(convertOpenSearchUnauthorized(e))
);
}
// forward 401 (boom) errors from legacy OpenSearch client
if (LegacyOpenSearchErrorHelpers.isNotAuthorizedError(e)) {
return e;
}
return hapiResponseAdapter.toInternalError();
}
}
}
const convertOpenSearchUnauthorized = (
e: OpenSearchNotAuthorizedError
): ErrorHttpResponseOptions => {
const getAuthenticateHeaderValue = () => {
const header = Object.entries(e.headers).find(
([key]) => key.toLowerCase() === 'www-authenticate'
);
return header ? header[1] : 'Basic realm="Authorization Required"';
};
return {
body: e.message,
headers: {
'www-authenticate': getAuthenticateHeaderValue(),
},
};
};
type WithoutHeadArgument<T> = T extends (first: any, ...rest: infer Params) => infer Return
? (...rest: Params) => Return
: never;
type RequestHandlerEnhanced<P, Q, B, Method extends RouteMethod> = WithoutHeadArgument<
RequestHandler<P, Q, B, Method>
>;
/**
* A function executed when route path matched requested resource path.
* Request handler is expected to return a result of one of {@link OpenSearchDashboardsResponseFactory} functions.
* @param context {@link RequestHandlerContext} - the core context exposed for this request.
* @param request {@link OpenSearchDashboardsRequest} - object containing information about requested resource,
* such as path, method, headers, parameters, query, body, etc.
* @param response {@link OpenSearchDashboardsResponseFactory} - a set of helper functions used to respond to a request.
*
* @example
* ```ts
* const router = httpSetup.createRouter();
* // creates a route handler for GET request on 'my-app/path/{id}' path
* router.get(
* {
* path: 'path/{id}',
* // defines a validation schema for a named segment of the route path
* validate: {
* params: schema.object({
* id: schema.string(),
* }),
* },
* },
* // function to execute to create a responses
* async (context, request, response) => {
* const data = await context.findObject(request.params.id);
* // creates a command to respond with 'not found' error
* if (!data) return response.notFound();
* // creates a command to send found data to the client
* return response.ok(data);
* }
* );
* ```
* @public
*/
export type RequestHandler<
P = unknown,
Q = unknown,
B = unknown,
Method extends RouteMethod = any,
ResponseFactory extends OpenSearchDashboardsResponseFactory = OpenSearchDashboardsResponseFactory
> = (
context: RequestHandlerContext,
request: OpenSearchDashboardsRequest<P, Q, B, Method>,
response: ResponseFactory
) => IOpenSearchDashboardsResponse<any> | Promise<IOpenSearchDashboardsResponse<any>>;
/**
* Type-safe wrapper for {@link RequestHandler} function.
* @example
* ```typescript
* export const wrapper: RequestHandlerWrapper = handler => {
* return async (context, request, response) => {
* // do some logic
* ...
* };
* }
* ```
* @public
*/
export type RequestHandlerWrapper = <
P,
Q,
B,
Method extends RouteMethod = any,
ResponseFactory extends OpenSearchDashboardsResponseFactory = OpenSearchDashboardsResponseFactory
>(
handler: RequestHandler<P, Q, B, Method, ResponseFactory>
) => RequestHandler<P, Q, B, Method, ResponseFactory>;