-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathhttp_tools.ts
148 lines (134 loc) · 4.94 KB
/
http_tools.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
/*
* 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 { readFileSync } from 'fs';
import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, Util } from 'hapi';
import Hoek from 'hoek';
import { ServerOptions as TLSOptions } from 'https';
import { ValidationError } from 'joi';
import { HttpConfig } from './http_config';
/**
* Converts Kibana `HttpConfig` into `ServerOptions` that are accepted by the Hapi server.
*/
export function getServerOptions(config: HttpConfig, { configureTLS = true } = {}) {
// Note that all connection options configured here should be exactly the same
// as in the legacy platform server (see `src/legacy/server/http/index`). Any change
// SHOULD BE applied in both places. The only exception is TLS-specific options,
// that are configured only here.
const options: ServerOptions = {
host: config.host,
port: config.port,
routes: {
cors: config.cors,
payload: {
maxBytes: config.maxPayload.getValueInBytes(),
},
validate: {
failAction: defaultValidationErrorHandler,
options: {
abortEarly: false,
},
},
},
state: {
strictHeader: false,
isHttpOnly: true,
isSameSite: false, // necessary to allow using Kibana inside an iframe
},
};
if (configureTLS && config.ssl.enabled) {
const ssl = config.ssl;
// TODO: Hapi types have a typo in `tls` property type definition: `https.RequestOptions` is used instead of
// `https.ServerOptions`, and `honorCipherOrder` isn't presented in `https.RequestOptions`.
const tlsOptions: TLSOptions = {
ca:
config.ssl.certificateAuthorities &&
config.ssl.certificateAuthorities.map(caFilePath => readFileSync(caFilePath)),
cert: readFileSync(ssl.certificate!),
ciphers: config.ssl.cipherSuites.join(':'),
// We use the server's cipher order rather than the client's to prevent the BEAST attack.
honorCipherOrder: true,
key: readFileSync(ssl.key!),
passphrase: ssl.keyPassphrase,
secureOptions: ssl.getSecureOptions(),
requestCert: ssl.requestCert,
};
options.tls = tlsOptions;
}
return options;
}
export function createServer(options: ServerOptions) {
const server = new Server(options);
// Revert to previous 120 seconds keep-alive timeout in Node < 8.
server.listener.keepAliveTimeout = 120e3;
server.listener.on('clientError', (err, socket) => {
if (socket.writable) {
socket.end(Buffer.from('HTTP/1.1 400 Bad Request\r\n\r\n', 'ascii'));
} else {
socket.destroy(err);
}
});
return server;
}
/**
* Hapi extends the ValidationError interface to add this output key with more data.
*/
export interface HapiValidationError extends ValidationError {
output: {
statusCode: number;
headers: Util.Dictionary<string | string[]>;
payload: {
statusCode: number;
error: string;
message?: string;
validation: {
source: string;
keys: string[];
};
};
};
}
/**
* Used to replicate Hapi v16 and below's validation responses. Should be used in the routes.validate.failAction key.
*/
export function defaultValidationErrorHandler(
request: Request,
h: ResponseToolkit,
err?: Error
): Lifecycle.ReturnValue {
// Newer versions of Joi don't format the key for missing params the same way. This shim
// provides backwards compatibility. Unfortunately, Joi doesn't export it's own Error class
// in JS so we have to rely on the `name` key before we can cast it.
//
// The Hapi code we're 'overwriting' can be found here:
// https://github.com/hapijs/hapi/blob/master/lib/validation.js#L102
if (err && err.name === 'ValidationError' && err.hasOwnProperty('output')) {
const validationError: HapiValidationError = err as HapiValidationError;
const validationKeys: string[] = [];
validationError.details.forEach(detail => {
if (detail.path.length > 0) {
validationKeys.push(Hoek.escapeHtml(detail.path.join('.')));
} else {
// If no path, use the value sigil to signal the entire value had an issue.
validationKeys.push('value');
}
});
validationError.output.payload.validation.keys = validationKeys;
}
throw err;
}