-
-
Notifications
You must be signed in to change notification settings - Fork 211
/
openapi.validator.ts
442 lines (400 loc) · 13.7 KB
/
openapi.validator.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
import { Options } from 'ajv';
import ono from 'ono';
import * as express from 'express';
import * as _uniq from 'lodash.uniq';
import * as middlewares from './middlewares';
import { Application, Response, NextFunction, Router } from 'express';
import { OpenApiContext } from './framework/openapi.context';
import { Spec } from './framework/openapi.spec.loader';
import {
NormalizedOpenApiValidatorOpts,
OpenApiValidatorOpts,
ValidateRequestOpts,
ValidateResponseOpts,
OpenApiRequest,
OpenApiRequestHandler,
OpenApiRequestMetadata,
ValidateSecurityOpts,
OpenAPIV3,
} from './framework/types';
import { defaultResolver } from './resolvers';
import { OperationHandlerOptions } from './framework/types';
import { defaultSerDes } from './framework/base.serdes';
import { SchemaPreprocessor } from './middlewares/parsers/schema.preprocessor';
import { AjvOptions } from './framework/ajv/options';
export {
OpenApiValidatorOpts,
InternalServerError,
UnsupportedMediaType,
RequestEntityTooLarge,
BadRequest,
MethodNotAllowed,
NotAcceptable,
NotFound,
Unauthorized,
Forbidden,
} from './framework/types';
export class OpenApiValidator {
readonly options: NormalizedOpenApiValidatorOpts;
readonly ajvOpts: AjvOptions;
constructor(options: OpenApiValidatorOpts) {
if (options.validateApiSpec == null) options.validateApiSpec = true;
if (options.validateRequests == null) options.validateRequests = true;
if (options.validateResponses == null) options.validateResponses = false;
if (options.validateSecurity == null) options.validateSecurity = true;
if (options.fileUploader == null) options.fileUploader = {};
if (options.$refParser == null) options.$refParser = { mode: 'bundle' };
if (options.validateFormats == null) options.validateFormats = true;
if (options.formats == null) options.formats = {};
if (typeof options.operationHandlers === 'string') {
/**
* Internally, we want to convert this to a value typed OperationHandlerOptions.
* In this way, we can treat the value as such when we go to install (rather than
* re-interpreting it over and over).
*/
options.operationHandlers = {
basePath: options.operationHandlers,
resolver: defaultResolver,
};
} else if (typeof options.operationHandlers !== 'object') {
// This covers cases where operationHandlers is null, undefined or false.
options.operationHandlers = false;
}
if (options.validateResponses === true) {
options.validateResponses = {
removeAdditional: false,
coerceTypes: false,
onError: null,
};
}
if (options.validateRequests === true) {
options.validateRequests = {
allowUnknownQueryParameters: false,
coerceTypes: false,
};
}
if (options.validateSecurity === true) {
options.validateSecurity = {};
}
this.validateOptions(options);
this.options = this.normalizeOptions(options);
this.ajvOpts = new AjvOptions(this.options);
}
installMiddleware(spec: Promise<Spec>): OpenApiRequestHandler[] {
const middlewares: OpenApiRequestHandler[] = [];
const pContext = spec
.then((spec) => {
const apiDoc = spec.apiDoc;
const ajvOpts = this.ajvOpts.preprocessor;
const resOpts = this.options.validateResponses as ValidateRequestOpts;
const sp = new SchemaPreprocessor(
apiDoc,
ajvOpts,
resOpts,
).preProcess();
return {
context: new OpenApiContext(spec, this.options.ignorePaths, this.options.ignoreUndocumented),
responseApiDoc: sp.apiDocRes,
error: null,
};
})
.catch((e) => {
return {
context: null,
responseApiDoc: null,
error: e,
};
});
const self = this; // using named functions instead of anonymous functions to allow traces to be more useful
let inited = false;
// install path params
middlewares.push(function pathParamsMiddleware(req, res, next) {
return pContext
.then(({ context, error }) => {
// Throw if any error occurred during spec load.
if (error) throw error;
if (!inited) {
// Would be nice to pass the current Router object here if the route
// is attach to a Router and not the app.
// Doing so would enable path params to be type coerced when provided to
// the final middleware.
// Unfortunately, it is not possible to get the current Router from a handler function
self.installPathParams(req.app, context);
inited = true;
}
next();
})
.catch(next);
});
// metadata middleware
let metamw;
middlewares.push(function metadataMiddleware(req, res, next) {
return pContext
.then(({ context, responseApiDoc }) => {
metamw = metamw || self.metadataMiddleware(context, responseApiDoc);
return metamw(req, res, next);
})
.catch(next);
});
if (this.options.fileUploader) {
// multipart middleware
let fumw;
middlewares.push(function multipartMiddleware(req, res, next) {
return pContext
.then(({ context: { apiDoc } }) => {
fumw = fumw || self.multipartMiddleware(apiDoc);
return fumw(req, res, next);
})
.catch(next);
});
}
// security middlware
let scmw;
middlewares.push(function securityMiddleware(req, res, next) {
return pContext
.then(({ context: { apiDoc } }) => {
const components = apiDoc.components;
if (self.options.validateSecurity && components?.securitySchemes) {
scmw = scmw || self.securityMiddleware(apiDoc);
return scmw(req, res, next);
} else {
next();
}
})
.catch(next);
});
// request middlweare
if (this.options.validateRequests) {
let reqmw;
middlewares.push(function requestMiddleware(req, res, next) {
return pContext
.then(({ context: { apiDoc } }) => {
reqmw = reqmw || self.requestValidationMiddleware(apiDoc);
return reqmw(req, res, next);
})
.catch(next);
});
}
// response middleware
if (this.options.validateResponses) {
let resmw;
middlewares.push(function responseMiddleware(req, res, next) {
return pContext
.then(({ responseApiDoc }) => {
resmw = resmw || self.responseValidationMiddleware(responseApiDoc);
return resmw(req, res, next);
})
.catch(next);
})
}
// op handler middleware
if (this.options.operationHandlers) {
let router: Router = null;
middlewares.push(function operationHandlersMiddleware(req, res, next) {
if (router) return router(req, res, next);
return pContext
.then(
({ context }) =>
(router = self.installOperationHandlers(req.baseUrl, context)),
)
.then((router) => router(req, res, next))
.catch(next);
});
}
return middlewares;
}
installPathParams(app: Application | Router, context: OpenApiContext): void {
const pathParams: string[] = [];
for (const route of context.routes) {
if (route.pathParams.length > 0) {
pathParams.push(...route.pathParams);
}
}
// install param on routes with paths
for (const p of _uniq(pathParams)) {
app.param(
p,
(
req: OpenApiRequest,
res: Response,
next: NextFunction,
value: any,
name: string,
) => {
const openapi = <OpenApiRequestMetadata>req.openapi;
if (openapi?.pathParams) {
const { pathParams } = openapi;
// override path params
req.params[name] = pathParams[name] || req.params[name];
}
next();
},
);
}
}
private metadataMiddleware(
context: OpenApiContext,
responseApiDoc: OpenAPIV3.Document,
) {
return middlewares.applyOpenApiMetadata(context, responseApiDoc);
}
private multipartMiddleware(apiDoc: OpenAPIV3.Document) {
return middlewares.multipart(apiDoc, {
multerOpts: this.options.fileUploader,
ajvOpts: this.ajvOpts.multipart,
});
}
private securityMiddleware(apiDoc: OpenAPIV3.Document) {
const securityHandlers = (<ValidateSecurityOpts>(
this.options.validateSecurity
))?.handlers;
return middlewares.security(apiDoc, securityHandlers);
}
private requestValidationMiddleware(apiDoc: OpenAPIV3.Document) {
const requestValidator = new middlewares.RequestValidator(
apiDoc,
this.ajvOpts.request,
);
return (req, res, next) => requestValidator.validate(req, res, next);
}
private responseValidationMiddleware(apiDoc: OpenAPIV3.Document) {
return new middlewares.ResponseValidator(
apiDoc,
this.ajvOpts.response,
// This has already been converted from boolean if required
this.options.validateResponses as ValidateResponseOpts,
).validate();
}
installOperationHandlers(baseUrl: string, context: OpenApiContext): Router {
const router = express.Router({ mergeParams: true });
this.installPathParams(router, context);
for (const route of context.routes) {
const { method, expressRoute } = route;
/**
* This if-statement is here to "narrow" the type of options.operationHandlers
* to OperationHandlerOptions (down from string | false | OperationHandlerOptions)
* At this point of execution it _should_ be impossible for this to NOT be the correct
* type as we re-assign during construction to verify this.
*/
if (this.isOperationHandlerOptions(this.options.operationHandlers)) {
const { basePath, resolver } = this.options.operationHandlers;
const path =
expressRoute.indexOf(baseUrl) === 0
? expressRoute.substring(baseUrl.length)
: expressRoute;
router[method.toLowerCase()](
path,
resolver(basePath, route, context.apiDoc),
);
}
}
return router;
}
private validateOptions(options: OpenApiValidatorOpts): void {
if (!options.apiSpec) throw ono('apiSpec required.');
const securityHandlers = (<any>options).securityHandlers;
if (securityHandlers != null) {
throw ono(
'securityHandlers is not supported. Use validateSecurities.handlers instead.',
);
}
if (options.coerceTypes) {
console.warn('coerceTypes is deprecated.');
}
const multerOpts = (<any>options).multerOpts;
if (multerOpts != null) {
throw ono('multerOpts is not supported. Use fileUploader instead.');
}
const unknownFormats = options.unknownFormats;
if (unknownFormats !== undefined) {
if (typeof unknownFormats === 'boolean') {
if (!unknownFormats) {
throw ono(
"unknownFormats must contain an array of unknownFormats, 'ignore' or true",
);
}
} else if (
typeof unknownFormats === 'string' &&
unknownFormats !== 'ignore' &&
!Array.isArray(unknownFormats)
)
throw ono(
"unknownFormats must contain an array of unknownFormats, 'ignore' or true",
);
console.warn('unknownFormats is deprecated.');
}
if (Array.isArray(options.formats)) {
console.warn(
'formats as an array is deprecated. Use object instead https://ajv.js.org/options.html#formats',
);
}
if (typeof options.validateFormats === 'string') {
console.warn(
`"validateFormats" as a string is deprecated. Set to a boolean and use "ajvFormats"`,
);
}
}
private normalizeOptions(
options: OpenApiValidatorOpts,
): NormalizedOpenApiValidatorOpts {
if (Array.isArray(options.formats)) {
const formats: Options['formats'] = {};
for (const { name, type, validate } of options.formats) {
if (type) {
const formatValidator:
| {
type: 'number';
validate: (x: number) => boolean;
}
| {
type: 'string';
validate: (x: string) => boolean;
} = { type, validate };
formats[name] = formatValidator;
} else {
formats[name] = validate;
}
}
options.formats = formats;
}
if (!options.serDes) {
options.serDes = defaultSerDes;
} else {
defaultSerDes.forEach((currentDefaultSerDes) => {
let defaultSerDesOverride = options.serDes.find(
(currentOptionSerDes) => {
return currentDefaultSerDes.format === currentOptionSerDes.format;
},
);
if (!defaultSerDesOverride) {
options.serDes.push(currentDefaultSerDes);
}
});
}
if (typeof options.validateFormats === 'string') {
if (!options.ajvFormats) {
options.ajvFormats = { mode: options.validateFormats };
}
options.validateFormats = true;
} else if (options.validateFormats && !options.ajvFormats) {
options.ajvFormats = { mode: 'fast' };
}
if (Array.isArray(options.unknownFormats)) {
for (const format of options.unknownFormats) {
options.formats[format] = true;
}
} else if (options.unknownFormats === 'ignore') {
options.validateFormats = false;
}
return options as NormalizedOpenApiValidatorOpts;
}
private isOperationHandlerOptions(
value: false | string | OperationHandlerOptions,
): value is OperationHandlerOptions {
if ((value as OperationHandlerOptions).resolver) {
return true;
} else {
return false;
}
}
}