-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
request.ts
274 lines (247 loc) · 8.64 KB
/
request.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
/*
* 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 { Url } from 'url';
import { Request, ApplicationState } from 'hapi';
import { Observable, fromEvent, merge } from 'rxjs';
import { shareReplay, first, takeUntil } from 'rxjs/operators';
import { RecursiveReadonly } from '@kbn/utility-types';
import { deepFreeze } from '../../../utils';
import { Headers } from './headers';
import { RouteMethod, RouteConfigOptions, validBodyOutput, isSafeMethod } from './route';
import { KibanaSocket, IKibanaSocket } from './socket';
import { RouteValidator, RouteValidatorFullConfig } from './validator';
const requestSymbol = Symbol('request');
/**
* @internal
*/
export interface KibanaRouteState extends ApplicationState {
xsrfRequired: boolean;
}
/**
* Route options: If 'GET' or 'OPTIONS' method, body options won't be returned.
* @public
*/
export type KibanaRequestRouteOptions<Method extends RouteMethod> = Method extends 'get' | 'options'
? Required<Omit<RouteConfigOptions<Method>, 'body'>>
: Required<RouteConfigOptions<Method>>;
/**
* Request specific route information exposed to a handler.
* @public
* */
export interface KibanaRequestRoute<Method extends RouteMethod> {
path: string;
method: Method;
options: KibanaRequestRouteOptions<Method>;
}
/**
* Request events.
* @public
* */
export interface KibanaRequestEvents {
/**
* Observable that emits once if and when the request has been aborted.
*/
aborted$: Observable<void>;
}
/**
* @deprecated
* `hapi` request object, supported during migration process only for backward compatibility.
* @public
*/
export interface LegacyRequest extends Request {} // eslint-disable-line @typescript-eslint/no-empty-interface
/**
* Kibana specific abstraction for an incoming request.
* @public
*/
export class KibanaRequest<
Params = unknown,
Query = unknown,
Body = unknown,
Method extends RouteMethod = any
> {
/**
* Factory for creating requests. Validates the request before creating an
* instance of a KibanaRequest.
* @internal
*/
public static from<P, Q, B>(
req: Request,
routeSchemas: RouteValidator<P, Q, B> | RouteValidatorFullConfig<P, Q, B> = {},
withoutSecretHeaders: boolean = true
) {
const routeValidator = RouteValidator.from<P, Q, B>(routeSchemas);
const requestParts = KibanaRequest.validate(req, routeValidator);
return new KibanaRequest(
req,
requestParts.params,
requestParts.query,
requestParts.body,
withoutSecretHeaders
);
}
/**
* Validates the different parts of a request based on the schemas defined for
* the route. Builds up the actual params, query and body object that will be
* received in the route handler.
* @internal
*/
private static validate<P, Q, B>(
req: Request,
routeValidator: RouteValidator<P, Q, B>
): {
params: P;
query: Q;
body: B;
} {
const params = routeValidator.getParams(req.params, 'request params');
const query = routeValidator.getQuery(req.query, 'request query');
const body = routeValidator.getBody(req.payload, 'request body');
return { query, params, body };
}
/** a WHATWG URL standard object. */
public readonly url: Url;
/** matched route details */
public readonly route: RecursiveReadonly<KibanaRequestRoute<Method>>;
/**
* Readonly copy of incoming request headers.
* @remarks
* This property will contain a `filtered` copy of request headers.
*/
public readonly headers: Headers;
/**
* Whether or not the request is a "system request" rather than an application-level request.
* Can be set on the client using the `HttpFetchOptions#asSystemRequest` option.
*/
public readonly isSystemRequest: boolean;
/** {@link IKibanaSocket} */
public readonly socket: IKibanaSocket;
/** Request events {@link KibanaRequestEvents} */
public readonly events: KibanaRequestEvents;
public readonly auth: {
/* true if the request has been successfully authenticated, otherwise false. */
isAuthenticated: boolean;
};
/** @internal */
protected readonly [requestSymbol]: Request;
constructor(
request: Request,
public readonly params: Params,
public readonly query: Query,
public readonly body: Body,
// @ts-expect-error we will use this flag as soon as http request proxy is supported in the core
// until that time we have to expose all the headers
private readonly withoutSecretHeaders: boolean
) {
this.url = request.url;
this.headers = deepFreeze({ ...request.headers });
this.isSystemRequest =
request.headers['kbn-system-request'] === 'true' ||
// Remove support for `kbn-system-api` in 8.x. Used only by legacy platform.
request.headers['kbn-system-api'] === 'true';
// prevent Symbol exposure via Object.getOwnPropertySymbols()
Object.defineProperty(this, requestSymbol, {
value: request,
enumerable: false,
});
this.route = deepFreeze(this.getRouteInfo(request));
this.socket = new KibanaSocket(request.raw.req.socket);
this.events = this.getEvents(request);
this.auth = {
// missing in fakeRequests, so we cast to false
isAuthenticated: Boolean(request.auth?.isAuthenticated),
};
}
private getEvents(request: Request): KibanaRequestEvents {
const finish$ = merge(
fromEvent(request.raw.req, 'end'), // all data consumed
fromEvent(request.raw.req, 'close') // connection was closed
).pipe(shareReplay(1), first());
return {
aborted$: fromEvent<void>(request.raw.req, 'aborted').pipe(first(), takeUntil(finish$)),
} as const;
}
private getRouteInfo(request: Request): KibanaRequestRoute<Method> {
const method = request.method as Method;
const { parse, maxBytes, allow, output } = request.route.settings.payload || {};
const options = ({
authRequired: this.getAuthRequired(request),
// some places in LP call KibanaRequest.from(request) manually. remove fallback to true before v8
xsrfRequired: (request.route.settings.app as KibanaRouteState)?.xsrfRequired ?? true,
tags: request.route.settings.tags || [],
body: isSafeMethod(method)
? undefined
: {
parse,
maxBytes,
accepts: allow,
output: output as typeof validBodyOutput[number], // We do not support all the HAPI-supported outputs and TS complains
},
} as unknown) as KibanaRequestRouteOptions<Method>; // TS does not understand this is OK so I'm enforced to do this enforced casting
return {
path: request.path,
method,
options,
};
}
private getAuthRequired(request: Request): boolean | 'optional' {
const authOptions = request.route.settings.auth;
if (typeof authOptions === 'object') {
// 'try' is used in the legacy platform
if (authOptions.mode === 'optional' || authOptions.mode === 'try') {
return 'optional';
}
if (authOptions.mode === 'required') {
return true;
}
}
// legacy platform routes
if (authOptions === undefined) {
return true;
}
if (authOptions === false) return false;
throw new Error(
`unexpected authentication options: ${JSON.stringify(authOptions)} for route: ${
this.url.href
}`
);
}
}
/**
* Returns underlying Hapi Request
* @internal
*/
export const ensureRawRequest = (request: KibanaRequest | LegacyRequest) =>
isKibanaRequest(request) ? request[requestSymbol] : request;
function isKibanaRequest(request: unknown): request is KibanaRequest {
return request instanceof KibanaRequest;
}
function isRequest(request: any): request is LegacyRequest {
try {
return request.raw.req && typeof request.raw.req === 'object';
} catch {
return false;
}
}
/**
* Checks if an incoming request either KibanaRequest or Legacy.Request
* @internal
*/
export function isRealRequest(request: unknown): request is KibanaRequest | LegacyRequest {
return isKibanaRequest(request) || isRequest(request);
}