Expand file tree
/
Copy pathserver.test.js
More file actions
387 lines (329 loc) · 13.3 KB
/
Copy pathserver.test.js
File metadata and controls
387 lines (329 loc) · 13.3 KB
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
const http = require('http');
const { request } = require('./test/http');
const mockValidateParams = jest.fn((req, res, next) => next());
const mockSearch = jest.fn((req, res) =>
res.status(200).json({
route: 'search',
params: req.searchParams
})
);
const mockWebSearch = jest.fn((req, res) =>
res.status(200).json({
route: 'webSearch',
body: req.body
})
);
const mockMorganMiddleware = jest.fn((req, res, next) => next());
const mockMorgan = jest.fn(() => mockMorganMiddleware);
mockMorgan.token = jest.fn();
jest.mock('morgan', () => mockMorgan);
jest.mock('./controllers/middleware', () => ({
validateParams: mockValidateParams
}));
jest.mock('./controllers/searchController', () => ({
SEARCH: mockSearch,
WEB_SEARCH: mockWebSearch
}));
const {
createApp,
createRequestLogger,
getRedactedRequestPath,
getRuntimeConfig,
handleRequestError,
startServer,
swaggerSetupOptions
} = require('./server');
function restoreEnv(name, value) {
if (value === undefined) {
delete process.env[name];
return;
}
process.env[name] = value;
}
describe('server application bootstrap', () => {
const originalBaseUrl = process.env.BASE_URL;
const originalNodeEnv = process.env.NODE_ENV;
const originalPort = process.env.PORT;
afterEach(() => {
restoreEnv('BASE_URL', originalBaseUrl);
restoreEnv('NODE_ENV', originalNodeEnv);
restoreEnv('PORT', originalPort);
jest.restoreAllMocks();
jest.clearAllMocks();
});
test('createApp mounts health check with CORS headers', async () => {
const response = await request(createApp(), {
path: '/api/health-check'
});
expect(response.status).toBe(200);
expect(response.text).toBe('');
expect(response.headers['access-control-allow-origin']).toBe('*');
expect(response.headers['x-request-id']).toMatch(/^[0-9a-f-]{36}$/);
});
test('createApp preserves valid caller request IDs in response headers', async () => {
const response = await request(createApp(), {
path: '/api/health-check',
headers: {
'X-Request-ID': 'caller-request-123'
}
});
expect(response.headers['x-request-id']).toBe('caller-request-123');
});
test('createApp mounts the OpenAPI JSON endpoint', async () => {
const response = await request(createApp(), {
path: '/api-docs/openapi.json'
});
expect(response.status).toBe(200);
expect(response.body.openapi).toBe('3.0.2');
expect(response.body.info.title).toBe('CVE Search API');
});
test('Swagger UI disables request submission without hiding documentation selectors', () => {
expect(swaggerSetupOptions.swaggerOptions.supportedSubmitMethods).toStrictEqual([]);
expect(swaggerSetupOptions.customCss).toContain('.swagger-ui .try-out { display: none }');
expect(swaggerSetupOptions.customCss).toContain('.swagger-ui .scheme-container { display: none }');
expect(swaggerSetupOptions.customCss).not.toContain('.swagger-ui select');
});
test('createApp parses JSON bodies before routing to webSearch', async () => {
const body = {
query: 'apache',
sort: {
property: 'cveId',
order: 'asc'
}
};
const response = await request(createApp(), {
method: 'POST',
path: '/webSearch',
body
});
expect(response.status).toBe(200);
expect(mockWebSearch).toHaveBeenCalledTimes(1);
expect(response.body).toStrictEqual({
route: 'webSearch',
body
});
});
test('createApp parses JSON bodies before routing to search', async () => {
const body = {
keywordSearch: 'apache',
resultsPerPage: 1
};
const response = await request(createApp(), {
method: 'POST',
path: '/search',
body
});
expect(response.status).toBe(200);
expect(mockSearch).toHaveBeenCalledTimes(1);
expect(response.body).toStrictEqual({
route: 'search',
params: {
scope: 'FULL',
...body
}
});
});
test('createApp returns a sanitized error for malformed JSON', async () => {
const response = await request(createApp(), {
method: 'POST',
path: '/search',
rawBody: '{"keywordSearch":',
headers: {
'Content-Type': 'application/json'
}
});
expect(response.status).toBe(400);
expect(response.body).toStrictEqual({
error: 'MALFORMED_JSON',
message: 'The request body contains malformed JSON.'
});
expect(response.headers['access-control-allow-origin']).toBe('*');
expect(mockSearch).not.toHaveBeenCalled();
});
test('createApp returns a sanitized error for unsupported JSON encoding', async () => {
const response = await request(createApp(), {
method: 'POST',
path: '/search',
rawBody: '{"keywordSearch":"apache"}',
headers: {
'Content-Type': 'application/json; charset=iso-8859-1'
}
});
expect(response.status).toBe(415);
expect(response.body).toStrictEqual({
error: 'SEARCH_CONTENT_TYPE',
message: 'The /search request body must use the application/json media type with UTF-8 encoding.'
});
expect(response.headers['access-control-allow-origin']).toBe('*');
expect(mockSearch).not.toHaveBeenCalled();
});
test.each([
['development', '/search'],
['development', '/webSearch'],
['production', '/search'],
['production', '/webSearch'],
[undefined, '/search'],
[undefined, '/webSearch']
])('oversized bodies return sanitized JSON in %s at %s', async (environment, path) => {
restoreEnv('NODE_ENV', environment);
const response = await request(createApp(), {
method: 'POST',
path,
body: { query: 'x'.repeat(102401) }
});
expect(response.status).toBe(413);
expect(response.headers['content-type']).toContain('application/json');
expect(response.headers['x-request-id']).toBeDefined();
expect(response.body).toStrictEqual({
error: 'REQUEST_BODY_TOO_LARGE',
message: 'The request body exceeds the allowed size limit.'
});
expect(mockSearch).not.toHaveBeenCalled();
expect(mockWebSearch).not.toHaveBeenCalled();
});
test('unsupported webSearch encoding returns sanitized JSON', async () => {
const response = await request(createApp(), {
method: 'POST',
path: '/webSearch',
rawBody: '{"query":"apache"}',
headers: { 'Content-Type': 'application/json; charset=iso-8859-1' }
});
expect(response.status).toBe(415);
expect(response.body).toStrictEqual({
error: 'REQUEST_ENCODING_UNSUPPORTED',
message: 'The request body uses an unsupported encoding.'
});
expect(mockWebSearch).not.toHaveBeenCalled();
});
test.each(['/search', '/webSearch'])('corrupt compressed bodies return sanitized JSON at %s', async (path) => {
const response = await request(createApp(), {
method: 'POST',
path,
rawBody: 'not-a-gzip-stream',
headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' }
});
expect(response.status).toBe(400);
expect(response.body).toStrictEqual({
error: 'INVALID_REQUEST',
message: 'The request could not be processed.'
});
expect(mockSearch).not.toHaveBeenCalled();
expect(mockWebSearch).not.toHaveBeenCalled();
});
test.each(['development', 'production'])(
'unexpected errors never expose exception details in %s',
async (environment) => {
process.env.NODE_ENV = environment;
mockSearch.mockImplementationOnce((_req, _res, next) => next(new Error('private backend credentials')));
const response = await request(createApp(), { method: 'POST', path: '/search', body: {} });
expect(response.status).toBe(500);
expect(response.body).toStrictEqual({
error: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected server error occurred. Please try again later.'
});
}
);
test('delegates errors after headers are sent without trying to rewrite the response', () => {
const failure = new Error('already streaming');
const res = { headersSent: true, status: jest.fn() };
const next = jest.fn();
handleRequestError(failure, {}, res, next);
expect(next).toHaveBeenCalledWith(failure);
expect(res.status).not.toHaveBeenCalled();
});
test.each([
[{ statusCode: 400 }, 400, 'INVALID_REQUEST'],
[{ status: 503 }, 503, 'INTERNAL_SERVER_ERROR'],
[{ status: 200 }, 500, 'INTERNAL_SERVER_ERROR']
])('preserves valid error statuses without forwarding details: %j', (failure, status, code) => {
const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
handleRequestError(failure, {}, res, jest.fn());
expect(res.status).toHaveBeenCalledWith(status);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: code }));
});
test('getRuntimeConfig preserves baseURL behavior when PORT is set without BASE_URL', () => {
delete process.env.BASE_URL;
process.env.PORT = '4567';
expect(getRuntimeConfig('4567')).toStrictEqual({
baseURL: 'http://127.0.0.1:4567'
});
});
test('getRuntimeConfig uses the effective default port when PORT is not configured', () => {
delete process.env.BASE_URL;
delete process.env.PORT;
expect(getRuntimeConfig(3000)).toStrictEqual({
baseURL: 'http://127.0.0.1:3000'
});
});
test('getRuntimeConfig uses BASE_URL when it is already configured', () => {
process.env.BASE_URL = 'https://search.example';
process.env.PORT = '4567';
expect(getRuntimeConfig('4567')).toStrictEqual({
baseURL: 'https://search.example'
});
});
test('getRedactedRequestPath omits query strings from logged URLs', () => {
expect(
getRedactedRequestPath({
path: '/search',
originalUrl: '/search?keywordSearch=apache'
})
).toBe('/search');
expect(
getRedactedRequestPath({
originalUrl: '/webSearch?query=apache'
})
).toBe('/webSearch');
});
test('createRequestLogger disables request logging in test environments', () => {
process.env.NODE_ENV = 'test';
const next = jest.fn();
createRequestLogger()({}, {}, next);
expect(next).toHaveBeenCalledTimes(1);
expect(mockMorgan).not.toHaveBeenCalled();
});
test('createRequestLogger uses a redacted request log format outside test environments', () => {
process.env.NODE_ENV = 'production';
createRequestLogger();
expect(mockMorgan.token).toHaveBeenCalledWith('redacted-url', getRedactedRequestPath);
expect(mockMorgan.token).toHaveBeenCalledWith('request-id', expect.any(Function));
expect(mockMorgan).toHaveBeenCalledWith(
':method :redacted-url :status :res[content-length] - :response-time ms request-id=:request-id',
{
skip: expect.any(Function)
}
);
});
test('startServer listens on the default port when PORT is not set', () => {
delete process.env.PORT;
const fakeServer = {};
fakeServer.listen = jest.fn(() => fakeServer);
const createServer = jest.spyOn(http, 'createServer').mockReturnValue(fakeServer);
expect(startServer()).toBe(fakeServer);
expect(createServer).toHaveBeenCalledWith(expect.any(Function));
expect(fakeServer.listen).toHaveBeenCalledWith(3000, expect.any(Function));
});
test('startServer passes through an explicit port', () => {
const fakeServer = {};
fakeServer.listen = jest.fn(() => fakeServer);
jest.spyOn(http, 'createServer').mockReturnValue(fakeServer);
expect(startServer('4567')).toBe(fakeServer);
expect(fakeServer.listen).toHaveBeenCalledWith('4567', expect.any(Function));
});
test('importing server does not start listening', () => {
const createServer = jest.spyOn(http, 'createServer');
jest.isolateModules(() => {
jest.doMock('morgan', () => mockMorgan);
jest.doMock('./controllers/middleware', () => ({
validateParams: jest.fn((req, res, next) => next())
}));
jest.doMock('./controllers/searchController', () => ({
SEARCH: jest.fn(),
WEB_SEARCH: jest.fn()
}));
const serverModule = require('./server');
expect(serverModule.startServer).toEqual(expect.any(Function));
expect(createServer).not.toHaveBeenCalled();
});
});
});