-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathrest.server.integration.ts
600 lines (541 loc) · 18 KB
/
rest.server.integration.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/rest
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {Application} from '@loopback/core';
import {
supertest,
expect,
createClientForHandler,
itSkippedOnTravis,
httpsGetAsync,
givenHttpServerConfig,
} from '@loopback/testlab';
import {RestBindings, RestServer, RestComponent} from '../..';
import {IncomingMessage, ServerResponse} from 'http';
import * as yaml from 'js-yaml';
import * as path from 'path';
import * as fs from 'fs';
import {RestServerConfig} from '../..';
const FIXTURES = path.resolve(__dirname, '../../../fixtures');
describe('RestServer (integration)', () => {
it('exports url property', async () => {
// Explicitly setting host to IPv4 address so test runs on Travis
const server = await givenAServer({rest: {port: 0, host: '127.0.0.1'}});
server.handler(dummyRequestHandler);
expect(server.url).to.be.undefined();
await server.start();
expect(server)
.to.have.property('url')
.which.is.a.String()
.match(/http|https\:\/\//);
await supertest(server.url)
.get('/')
.expect(200, 'Hello');
await server.stop();
expect(server.url).to.be.undefined();
});
it('updates rest.port binding when listening on ephemeral port', async () => {
const server = await givenAServer({rest: {port: 0}});
await server.start();
expect(server.getSync(RestBindings.PORT)).to.be.above(0);
await server.stop();
});
it('honors port binding after instantiation', async () => {
const server = await givenAServer({rest: {port: 80}});
server.bind(RestBindings.PORT).to(0);
await server.start();
expect(server.getSync(RestBindings.PORT)).to.not.equal(80);
await server.stop();
});
it('does not throw an error when stopping an app that has not been started', async () => {
const server = await givenAServer();
await expect(server.stop()).to.fulfilled();
});
it('responds with 500 when Sequence fails with unhandled error', async () => {
const server = await givenAServer({rest: {port: 0}});
server.handler((context, sequence) => {
return Promise.reject(new Error('unhandled test error'));
});
// Temporarily disable Mocha's handling of uncaught exceptions
const mochaListeners = process.listeners('uncaughtException');
process.removeAllListeners('uncaughtException');
process.once('uncaughtException', err => {
expect(err).to.have.property('message', 'unhandled test error');
for (const l of mochaListeners) {
process.on('uncaughtException', l);
}
});
return createClientForHandler(server.requestHandler)
.get('/')
.expect(500);
});
it('allows static assets to be mounted at /', async () => {
const root = FIXTURES;
const server = await givenAServer({
rest: {
port: 0,
},
});
expect(() => server.static('/', root)).to.not.throw();
expect(() => server.static('', root)).to.not.throw();
expect(() => server.static(['/'], root)).to.not.throw();
expect(() => server.static(['/html', ''], root)).to.not.throw();
expect(() => server.static(/.*/, root)).to.not.throw();
expect(() => server.static('/(.*)', root)).to.not.throw();
});
it('allows static assets via api', async () => {
const root = FIXTURES;
const server = await givenAServer({
rest: {
port: 0,
},
});
server.static('/html', root);
const content = fs
.readFileSync(path.join(root, 'index.html'))
.toString('utf-8');
await createClientForHandler(server.requestHandler)
.get('/html/index.html')
.expect('Content-Type', /text\/html/)
.expect(200, content);
});
it('allows static assets via api after start', async () => {
const root = FIXTURES;
const server = await givenAServer({
rest: {
port: 0,
},
});
await createClientForHandler(server.requestHandler)
.get('/html/index.html')
.expect(404);
server.static('/html', root);
await createClientForHandler(server.requestHandler)
.get('/html/index.html')
.expect(200);
});
it('allows non-static routes after assets', async () => {
const root = FIXTURES;
const server = await givenAServer({
rest: {
port: 0,
},
});
server.static('/html', root);
server.handler(dummyRequestHandler);
await createClientForHandler(server.requestHandler)
.get('/html/does-not-exist.html')
.expect(200, 'Hello');
});
it('gives precedence to API routes over static assets', async () => {
const root = FIXTURES;
const server = await givenAServer({
rest: {
port: 0,
},
});
server.static('/html', root);
server.handler(dummyRequestHandler);
await createClientForHandler(server.requestHandler)
.get('/html/index.html')
.expect(200, 'Hello');
});
it('allows cors', async () => {
const server = await givenAServer({rest: {port: 0}});
server.handler(dummyRequestHandler);
await createClientForHandler(server.requestHandler)
.get('/')
.expect(200, 'Hello')
.expect('Access-Control-Allow-Origin', '*')
.expect('Access-Control-Allow-Credentials', 'true');
});
it('allows cors preflight', async () => {
const server = await givenAServer({rest: {port: 0}});
server.handler(dummyRequestHandler);
await createClientForHandler(server.requestHandler)
.options('/')
.expect(204)
.expect('Access-Control-Allow-Origin', '*')
.expect('Access-Control-Allow-Credentials', 'true')
.expect('Access-Control-Max-Age', '86400');
});
it('allows custom CORS configuration', async () => {
const server = await givenAServer({
rest: {
port: 0,
cors: {
optionsSuccessStatus: 200,
maxAge: 1,
},
},
});
server.handler(dummyRequestHandler);
await createClientForHandler(server.requestHandler)
.options('/')
.expect(200)
.expect('Access-Control-Max-Age', '1');
});
it('exposes "GET /openapi.json" endpoint', async () => {
const server = await givenAServer({
rest: {
port: 0,
},
});
const greetSpec = {
responses: {
200: {
content: {'text/plain': {schema: {type: 'string'}}},
description: 'greeting of the day',
},
},
};
server.route('get', '/greet', greetSpec, function greet() {});
const response = await createClientForHandler(server.requestHandler).get(
'/openapi.json',
);
expect(response.body).to.containDeep({
openapi: '3.0.0',
info: {
title: 'LoopBack Application',
version: '1.0.0',
},
servers: [{url: '/'}],
paths: {
'/greet': {
get: {
responses: {
'200': {
content: {
'text/plain': {
schema: {type: 'string'},
},
},
description: 'greeting of the day',
},
},
},
},
},
});
expect(response.get('Access-Control-Allow-Origin')).to.equal('*');
expect(response.get('Access-Control-Allow-Credentials')).to.equal('true');
});
it('exposes "GET /openapi.json" with openApiSpec.servers', async () => {
const server = await givenAServer({
rest: {
port: 0,
openApiSpec: {
servers: [{url: 'http://127.0.0.1:8080'}],
},
},
});
const response = await createClientForHandler(server.requestHandler).get(
'/openapi.json',
);
expect(response.body.servers).to.eql([{url: 'http://127.0.0.1:8080'}]);
});
it('exposes "GET /openapi.json" with openApiSpec.setServersFromRequest', async () => {
const server = await givenAServer({
rest: {
port: 0,
openApiSpec: {
setServersFromRequest: true,
},
},
});
const response = await createClientForHandler(server.requestHandler).get(
'/openapi.json',
);
expect(response.body.servers[0].url).to.match(/http:\/\/127.0.0.1\:\d+/);
});
it('exposes endpoints with openApiSpec.endpointMapping', async () => {
const server = await givenAServer({
rest: {
port: 0,
openApiSpec: {
endpointMapping: {
'/openapi': {version: '3.0.0', format: 'yaml'},
},
},
},
});
const test = createClientForHandler(server.requestHandler);
await test.get('/openapi').expect(200, /openapi\: 3\.0\.0/);
await test.get('/openapi.json').expect(404);
});
it('exposes "GET /openapi.yaml" endpoint', async () => {
const server = await givenAServer({rest: {port: 0}});
const greetSpec = {
responses: {
200: {
content: {'text/plain': {schema: {type: 'string'}}},
description: 'greeting of the day',
},
},
};
server.route('get', '/greet', greetSpec, function greet() {});
const response = await createClientForHandler(server.requestHandler).get(
'/openapi.yaml',
);
const expected = yaml.safeLoad(`
openapi: 3.0.0
info:
title: LoopBack Application
version: 1.0.0
paths:
/greet:
get:
responses:
'200':
description: greeting of the day
content:
'text/plain':
schema:
type: string
`);
// Use json for comparison to tolerate textual diffs
const json = yaml.safeLoad(response.text);
expect(json).to.containDeep(expected);
expect(json.servers[0].url).to.match('/');
expect(response.get('Access-Control-Allow-Origin')).to.equal('*');
expect(response.get('Access-Control-Allow-Credentials')).to.equal('true');
});
it('exposes "GET /explorer" endpoint', async () => {
const app = new Application();
app.component(RestComponent);
const server = await app.getServer(RestServer);
const greetSpec = {
responses: {
200: {
schema: {type: 'string'},
description: 'greeting of the day',
},
},
};
server.route('get', '/greet', greetSpec, function greet() {});
const response = await createClientForHandler(server.requestHandler).get(
'/explorer',
);
await server.get(RestBindings.PORT);
const expectedUrl = new RegExp(
[
'http://explorer.loopback.io',
'\\?url=http://\\d+.\\d+.\\d+.\\d+:\\d+/openapi.json',
].join(''),
);
expect(response.get('Location')).match(expectedUrl);
expect(response.get('Access-Control-Allow-Origin')).to.equal('*');
expect(response.get('Access-Control-Allow-Credentials')).to.equal('true');
});
it('honors "x-forwarded-*" headers', async () => {
const app = new Application();
app.component(RestComponent);
const server = await app.getServer(RestServer);
const response = await createClientForHandler(server.requestHandler)
.get('/explorer')
.set('x-forwarded-proto', 'https')
.set('x-forwarded-host', 'example.com')
.set('x-forwarded-port', '8080');
await server.get(RestBindings.PORT);
const expectedUrl = new RegExp(
[
'https://explorer.loopback.io',
'\\?url=https://example.com:8080/openapi.json',
].join(''),
);
expect(response.get('Location')).match(expectedUrl);
});
it('honors "x-forwarded-host" headers', async () => {
const app = new Application();
app.component(RestComponent);
const server = await app.getServer(RestServer);
const response = await createClientForHandler(server.requestHandler)
.get('/explorer')
.set('x-forwarded-proto', 'http')
.set('x-forwarded-host', 'example.com:8080,my.example.com:9080');
await server.get(RestBindings.PORT);
const expectedUrl = new RegExp(
[
'http://explorer.loopback.io',
'\\?url=http://example.com:8080/openapi.json',
].join(''),
);
expect(response.get('Location')).match(expectedUrl);
});
it('skips port if it is the default for http or https', async () => {
const app = new Application();
app.component(RestComponent);
const server = await app.getServer(RestServer);
const response = await createClientForHandler(server.requestHandler)
.get('/explorer')
.set('x-forwarded-proto', 'https')
.set('x-forwarded-host', 'example.com')
.set('x-forwarded-port', '443');
await server.get(RestBindings.PORT);
const expectedUrl = new RegExp(
[
'https://explorer.loopback.io',
'\\?url=https://example.com/openapi.json',
].join(''),
);
expect(response.get('Location')).match(expectedUrl);
});
it('exposes "GET /explorer" endpoint with apiExplorer.url', async () => {
const server = await givenAServer({
rest: {
apiExplorer: {
url: 'https://petstore.swagger.io',
},
},
});
const response = await createClientForHandler(server.requestHandler).get(
'/explorer',
);
await server.get(RestBindings.PORT);
const expectedUrl = new RegExp(
[
'https://petstore.swagger.io',
'\\?url=http://\\d+.\\d+.\\d+.\\d+:\\d+/openapi.json',
].join(''),
);
expect(response.get('Location')).match(expectedUrl);
});
it('exposes "GET /explorer" endpoint with apiExplorer.urlForHttp', async () => {
const server = await givenAServer({
rest: {
apiExplorer: {
url: 'https://petstore.swagger.io',
httpUrl: 'http://petstore.swagger.io',
},
},
});
const response = await createClientForHandler(server.requestHandler).get(
'/explorer',
);
await server.get(RestBindings.PORT);
const expectedUrl = new RegExp(
[
'http://petstore.swagger.io',
'\\?url=http://\\d+.\\d+.\\d+.\\d+:\\d+/openapi.json',
].join(''),
);
expect(response.get('Location')).match(expectedUrl);
});
it('supports HTTPS protocol with key and certificate files', async () => {
const keyPath = path.join(FIXTURES, 'key.pem');
const certPath = path.join(FIXTURES, 'cert.pem');
const options = {
port: 0,
protocol: 'https',
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath),
};
const serverOptions = givenHttpServerConfig(options);
const server = await givenAServer({rest: serverOptions});
server.handler(dummyRequestHandler);
await server.start();
const serverUrl = server.getSync(RestBindings.URL);
const res = await httpsGetAsync(serverUrl);
expect(res.statusCode).to.equal(200);
});
it('supports HTTPS protocol with a pfx file', async () => {
const pfxPath = path.join(FIXTURES, 'pfx.pfx');
const options = {
port: 0,
protocol: 'https',
pfx: fs.readFileSync(pfxPath),
passphrase: 'loopback4',
};
const serverOptions = givenHttpServerConfig(options);
const server = await givenAServer({rest: serverOptions});
server.handler(dummyRequestHandler);
await server.start();
const serverUrl = server.getSync(RestBindings.URL);
const res = await httpsGetAsync(serverUrl);
expect(res.statusCode).to.equal(200);
await server.stop();
});
itSkippedOnTravis('handles IPv6 loopback address in HTTPS', async () => {
const keyPath = path.join(FIXTURES, 'key.pem');
const certPath = path.join(FIXTURES, 'cert.pem');
const server = await givenAServer({
rest: {
port: 0,
host: '::1',
protocol: 'https',
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath),
},
});
server.handler(dummyRequestHandler);
await server.start();
const serverUrl = server.getSync(RestBindings.URL);
const res = await httpsGetAsync(serverUrl);
expect(res.statusCode).to.equal(200);
await server.stop();
});
// https://github.com/strongloop/loopback-next/issues/1623
itSkippedOnTravis('handles IPv6 address for API Explorer UI', async () => {
const keyPath = path.join(FIXTURES, 'key.pem');
const certPath = path.join(FIXTURES, 'cert.pem');
const server = await givenAServer({
rest: {
port: 0,
host: '::1',
protocol: 'https',
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath),
},
});
server.handler(dummyRequestHandler);
await server.start();
const serverUrl = server.getSync(RestBindings.URL);
// The `Location` header should be something like
// https://explorer.loopback.io?url=https://[::1]:58470/openapi.json
const res = await httpsGetAsync(serverUrl + '/explorer');
const location = res.headers['location'];
expect(location).to.match(/\[\:\:1\]\:\d+\/openapi.json/);
expect(location).to.equal(
`https://explorer.loopback.io?url=${serverUrl}/openapi.json`,
);
await server.stop();
});
it('honors HTTPS config binding after instantiation', async () => {
const keyPath = path.join(FIXTURES, 'key.pem');
const certPath = path.join(FIXTURES, 'cert.pem');
const options = {
port: 0,
protocol: 'https',
};
const serverOptions = givenHttpServerConfig(options);
const server = await givenAServer({rest: serverOptions});
server.handler(dummyRequestHandler);
await server.start();
let serverUrl = server.getSync(RestBindings.URL);
await expect(httpsGetAsync(serverUrl)).to.be.rejectedWith(/EPROTO/);
await server.stop();
server.bind(RestBindings.HTTPS_OPTIONS).to({
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath),
});
await server.start();
serverUrl = server.getSync(RestBindings.URL);
const res = await httpsGetAsync(serverUrl);
expect(res.statusCode).to.equal(200);
await server.stop();
});
async function givenAServer(options?: {rest: RestServerConfig}) {
const app = new Application(options);
app.component(RestComponent);
return await app.getServer(RestServer);
}
function dummyRequestHandler(handler: {
request: IncomingMessage;
response: ServerResponse;
}) {
const {response} = handler;
response.write('Hello');
response.end();
}
});