-
-
Notifications
You must be signed in to change notification settings - Fork 202
/
openapi.request.validator.ts
331 lines (305 loc) 路 10.5 KB
/
openapi.request.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
import { Ajv, ValidateFunction } from 'ajv';
import { createRequestAjv } from '../framework/ajv';
import {
ContentType,
ajvErrorsToValidatorError,
augmentAjvErrors,
} from './util';
import { NextFunction, RequestHandler, Response } from 'express';
import {
OpenAPIV3,
OpenApiRequest,
RequestValidatorOptions,
ValidateRequestOpts,
OpenApiRequestMetadata,
NotFound,
BadRequest,
ParametersSchema,
BodySchema,
ValidationSchema,
} from '../framework/types';
import { BodySchemaParser } from './parsers/body.parse';
import { ParametersSchemaParser } from './parsers/schema.parse';
import { RequestParameterMutator } from './parsers/req.parameter.mutator';
type OperationObject = OpenAPIV3.OperationObject;
type SchemaObject = OpenAPIV3.SchemaObject;
type ReferenceObject = OpenAPIV3.ReferenceObject;
type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject;
type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject;
type ApiKeySecurityScheme = OpenAPIV3.ApiKeySecurityScheme;
export class RequestValidator {
private middlewareCache: { [key: string]: RequestHandler } = {};
private apiDoc: OpenAPIV3.Document;
private ajv: Ajv;
private ajvBody: Ajv;
private requestOpts: ValidateRequestOpts = {};
constructor(
apiDoc: OpenAPIV3.Document,
options: RequestValidatorOptions = {},
) {
this.middlewareCache = {};
this.apiDoc = apiDoc;
this.requestOpts.allowUnknownQueryParameters =
options.allowUnknownQueryParameters;
this.ajv = createRequestAjv(apiDoc, { ...options, coerceTypes: true });
this.ajvBody = createRequestAjv(apiDoc, options);
}
public validate(
req: OpenApiRequest,
res: Response,
next: NextFunction,
): void {
if (!req.openapi) {
// this path was not found in open api and
// this path is not defined under an openapi base path
// skip it
return next();
}
const openapi = <OpenApiRequestMetadata>req.openapi;
const path = openapi.expressRoute;
const reqSchema = openapi.schema;
// cache middleware by combining method, path, and contentType
const contentType = ContentType.from(req);
const contentTypeKey = contentType.equivalents()[0] ?? 'not_provided';
// use openapi.expressRoute as path portion of key
const key = `${req.method}-${path}-${contentTypeKey}`;
if (!this.middlewareCache[key]) {
const middleware = this.buildMiddleware(path, reqSchema, contentType);
this.middlewareCache[key] = middleware;
}
return this.middlewareCache[key](req, res, next);
}
private buildMiddleware(
path: string,
reqSchema: OperationObject,
contentType: ContentType,
): RequestHandler {
const apiDoc = this.apiDoc;
const schemaParser = new ParametersSchemaParser(this.ajv, apiDoc);
const parameters = schemaParser.parse(path, reqSchema.parameters);
const securityQueryParam = Security.queryParam(apiDoc, reqSchema);
const body = new BodySchemaParser().parse(path, reqSchema, contentType);
const validator = new Validator(this.apiDoc, parameters, body, {
general: this.ajv,
body: this.ajvBody,
});
const allowUnknownQueryParameters = !!(
reqSchema['x-allow-unknown-query-parameters'] ??
this.requestOpts.allowUnknownQueryParameters
);
return (req: OpenApiRequest, res: Response, next: NextFunction): void => {
const openapi = <OpenApiRequestMetadata>req.openapi;
const pathParams = Object.keys(openapi.pathParams);
const hasPathParams = pathParams.length > 0;
if (hasPathParams) {
// handle wildcard path param syntax
if (openapi.expressRoute.endsWith('*')) {
// if we have an express route /data/:p*, we require a path param, p
// if the p param is empty, the user called /p which is not found
// if it was found, it would match a different route
if (pathParams.filter((p) => openapi.pathParams[p]).length === 0) {
throw new NotFound({
path: req.path,
message: 'not found',
});
}
}
req.params = openapi.pathParams ?? req.params;
}
const schemaProperties = validator.allSchemaProperties;
const mutator = new RequestParameterMutator(
this.ajv,
apiDoc,
path,
schemaProperties,
);
mutator.modifyRequest(req);
if (!allowUnknownQueryParameters) {
this.processQueryParam(
req.query,
schemaProperties.query,
securityQueryParam,
);
}
const cookies = req.cookies
? {
...req.cookies,
...req.signedCookies,
}
: undefined;
const data = {
query: req.query ?? {},
headers: req.headers,
params: req.params,
cookies,
body: req.body,
};
const schemaBody = <any>validator?.schemaBody;
const discriminator = schemaBody?.properties?.body?._discriminator;
const discriminatorValidator = this.discriminatorValidator(
req,
discriminator,
);
const validatorBody = discriminatorValidator ?? validator.validatorBody;
const valid = validator.validatorGeneral(data);
const validBody = validatorBody(
discriminatorValidator ? data.body : data,
);
if (valid && validBody) {
next();
} else {
const errors = augmentAjvErrors(
[]
.concat(validator.validatorGeneral.errors ?? [])
.concat(validatorBody.errors ?? []),
);
const err = ajvErrorsToValidatorError(400, errors);
const message = this.ajv.errorsText(errors, { dataVar: 'request' });
const error: BadRequest = new BadRequest({
path: req.path,
message: message,
});
error.errors = err.errors;
throw error;
}
};
}
private discriminatorValidator(req, discriminator) {
if (discriminator) {
const { options, property, validators } = discriminator;
const discriminatorValue = req.body[property]; // TODO may not always be in this position
if (options.find((o) => o.option === discriminatorValue)) {
return validators[discriminatorValue];
} else {
throw new BadRequest({
path: req.path,
message: `'${property}' should be equal to one of the allowed values: ${options
.map((o) => o.option)
.join(', ')}.`,
});
}
}
return null;
}
private processQueryParam(query: object, schema, whiteList: string[] = []) {
const entries = Object.entries(schema.properties ?? {});
let keys = [];
for (const [key, prop] of entries) {
if (prop['type'] === 'object' && prop['additionalProperties']) {
// we have an object that allows additional properties
return;
}
keys.push(key);
}
const knownQueryParams = new Set(keys);
whiteList.forEach((item) => knownQueryParams.add(item));
const queryParams = Object.keys(query);
const allowedEmpty = schema.allowEmptyValue;
for (const q of queryParams) {
if (!knownQueryParams.has(q)) {
throw new BadRequest({
path: `.query.${q}`,
message: `Unknown query parameter '${q}'`,
});
} else if (!allowedEmpty?.has(q) && (query[q] === '' || null)) {
throw new BadRequest({
path: `.query.${q}`,
message: `Empty value found for query parameter '${q}'`,
});
}
}
}
}
class Validator {
private readonly apiDoc: OpenAPIV3.Document;
readonly schemaGeneral: object;
readonly schemaBody: object;
readonly validatorGeneral: ValidateFunction;
readonly validatorBody: ValidateFunction;
readonly allSchemaProperties: ValidationSchema;
constructor(
apiDoc: OpenAPIV3.Document,
parametersSchema: ParametersSchema,
bodySchema: BodySchema,
ajv: {
general: Ajv;
body: Ajv;
},
) {
this.apiDoc = apiDoc;
this.schemaGeneral = this._schemaGeneral(parametersSchema);
this.schemaBody = this._schemaBody(bodySchema);
this.allSchemaProperties = {
...(<any>this.schemaGeneral).properties, // query, header, params props
body: (<any>this.schemaBody).properties.body, // body props
};
this.validatorGeneral = ajv.general.compile(this.schemaGeneral);
this.validatorBody = ajv.body.compile(this.schemaBody);
}
private _schemaGeneral(parameters: ParametersSchema): object {
// $schema: "http://json-schema.org/draft-04/schema#",
return {
paths: this.apiDoc.paths,
components: this.apiDoc.components,
required: ['query', 'headers', 'params'],
properties: { ...parameters, body: {} },
};
}
private _schemaBody(body: BodySchema): object {
// $schema: "http://json-schema.org/draft-04/schema#"
const isBodyBinary = body?.['format'] === 'binary';
const bodyProps = isBodyBinary ? {} : body;
const bodySchema = {
paths: this.apiDoc.paths,
components: this.apiDoc.components,
properties: {
query: {},
headers: {},
params: {},
cookies: {},
body: bodyProps,
},
};
const requireBody = (<SchemaObject>body).required && !isBodyBinary;
if (requireBody) {
(<any>bodySchema).required = ['body'];
}
return bodySchema;
}
}
class Security {
public static queryParam(
apiDocs: OpenAPIV3.Document,
schema: OperationObject,
): string[] {
const hasPathSecurity = schema.security?.length > 0 ?? false;
const hasRootSecurity = apiDocs.security?.length > 0 ?? false;
let usedSecuritySchema: SecurityRequirementObject[] = [];
if (hasPathSecurity) {
usedSecuritySchema = schema.security;
} else if (hasRootSecurity) {
// if no security schema for the path, use top-level security schema
usedSecuritySchema = apiDocs.security;
}
const securityQueryParameter = this.getSecurityQueryParams(
usedSecuritySchema,
apiDocs.components?.securitySchemes,
);
return securityQueryParameter;
}
private static getSecurityQueryParams(
usedSecuritySchema: SecurityRequirementObject[],
securitySchema: { [key: string]: ReferenceObject | SecuritySchemeObject },
): string[] {
return usedSecuritySchema && securitySchema
? usedSecuritySchema
.filter((obj) => Object.entries(obj).length !== 0)
.map((sec) => {
const securityKey = Object.keys(sec)[0];
return <SecuritySchemeObject>securitySchema[securityKey];
})
.filter((sec) => sec?.type === 'apiKey' && sec?.in == 'query')
.map((sec: ApiKeySecurityScheme) => sec.name)
: [];
}
}