forked from Eywek/typoa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.ts
More file actions
792 lines (770 loc) 路 21.9 KB
/
Copy pathvalidator.ts
File metadata and controls
792 lines (770 loc) 路 21.9 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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
import express from 'express'
import { OpenAPIV3 } from 'openapi-types'
import { buildRef } from '../resolve'
import { BodyDiscriminatorFunction } from './decorators'
import { options } from '../option'
import { CustomLogger } from '../logger'
const { features } = options
type ValidationErrorDetail = { errorMessage: string; fieldName: string }
export class ValidateError extends Error {
public status = 400
public name = 'ValidateError'
constructor(
public fields: Record<
string,
{
message: string
value?: any
details?: Array<ValidationErrorDetail>
}
>,
public message: string
) {
super(message)
}
}
export async function validateAndParse(
req: express.Request,
schemas: OpenAPIV3.ComponentsObject['schemas'],
rules: {
params: OpenAPIV3.ParameterObject[]
body?: OpenAPIV3.RequestBodyObject
bodyDiscriminatorFn?: BodyDiscriminatorFunction
}
): Promise<any[]> {
const logger = options.getCustomLogger()
const args: any[] = []
for (const param of rules.params || []) {
// Handling @Request()
if (param.in === 'request') {
args.push(req)
continue
}
// Handling body
if (param.in === 'body') {
args.push(
await validateBody(
req,
rules.body!,
rules.bodyDiscriminatorFn,
schemas,
logger
)
)
continue
}
// Handling other params: header, query and path
let value: string | undefined | string[]
switch (param.in) {
case 'header':
value = req.headers[param.name]
break
case 'query':
value = req.query[param.name] as string | undefined | string[]
const schema = param.schema!
if (
'type' in schema &&
schema.type === 'boolean' &&
value?.length === 0
) {
value = 'true' // allow empty values for param boolean
}
if (
'type' in schema &&
schema.type === 'array' &&
typeof value === 'string'
) {
value = [value]
}
break
case 'path':
value = req.params[param.name]
break
}
const isUndefined = typeof value === 'undefined'
if (param.required === true && isUndefined) {
throw new ValidateError(
{
[param.name]: {
message: 'Param is required',
value
}
},
'Missing parameter'
)
}
// Don't validate
if (isUndefined) {
args.push(undefined)
continue
}
const validationResponse = validateAndParseValueAgainstSchema(
param.name,
value,
param.schema!,
schemas,
'unknown',
logger
)
if (!validationResponse.succeed) {
throw new ValidateError(
{
[param.name]: {
message: validationResponse.errorMessage,
value,
details: validationResponse.details
}
},
'Missing parameter'
)
}
args.push(validationResponse.value)
}
return args
}
export function validateAndParseResponse(
data: unknown,
schemas: OpenAPIV3.ComponentsObject['schemas'],
rules: Record<string, OpenAPIV3.ResponseObject>,
statusCode: string,
contentType: string
): unknown {
const logger = options.getCustomLogger()
try {
const rule = rules[statusCode] ?? rules.default
if (!rule)
throw new ValidateError(
{
response: {
message: `Missing response schema for status code ${statusCode}`
}
},
'Invalid status code'
)
const expectedSchema = rule.content?.[contentType]?.schema
if (typeof expectedSchema === 'undefined') {
if (typeof data === 'undefined' || data === null) {
return data
}
logger.error(`Schema is not found for '${contentType}', throwing error`)
throw new ValidateError({}, 'This content-type is not allowed')
}
const ValidationResponse = validateAndParseValueAgainstSchema(
'response',
data,
expectedSchema,
schemas,
'unknown',
logger
)
if (!ValidationResponse.succeed) {
throw new ValidateError(
{ response: { message: ValidationResponse.errorMessage } },
'Invalid response'
)
}
return ValidationResponse.value
} catch (e) {
if (e instanceof ValidateError) {
// validation error on the result is a server, not client error
e.status = 500
}
throw e
}
}
async function validateBody(
req: express.Request,
rule: OpenAPIV3.RequestBodyObject,
discriminatorFn: BodyDiscriminatorFunction | undefined,
schemas: OpenAPIV3.ComponentsObject['schemas'],
logger: CustomLogger
): Promise<unknown> {
const body = req.body
const contentType = (req.headers['content-type'] ?? 'application/json').split(';')[0]
const expectedSchema = rule.content[contentType]?.schema
if (typeof expectedSchema === 'undefined') {
logger.error(`Schema is not found for '${contentType}', throwing error`)
throw new ValidateError({}, 'This content-type is not allowed')
}
if (req.readableEnded === false) {
logger.debug(`Body has not be parsed, body validation skipped!`)
return body
}
if (discriminatorFn) {
const schemaName = await discriminatorFn(req)
const validationResult = validateAndParseValueAgainstSchema(
'body',
body,
{ $ref: buildRef(schemaName) },
schemas,
'unknown',
logger
)
if (validationResult.succeed) {
return validationResult.value
}
// Extract the failing value from the body based on the field path
const fieldPath = validationResult.fieldName || 'body'
const failingValue =
fieldPath === 'body'
? body
: getNestedValue(body, fieldPath.replace('body.', ''))
const errorField: {
message: string
value?: any
details: Array<ValidationErrorDetail>
} = {
message: validationResult.errorMessage,
details: validationResult.details ?? []
}
if (failingValue !== null && failingValue !== undefined) {
errorField.value = failingValue
}
throw new ValidateError(
{
[fieldPath]: errorField
},
validationResult.errorMessage
)
}
const validationResult = validateAndParseValueAgainstSchema(
'body',
body,
expectedSchema,
schemas,
'unknown',
logger
)
if (validationResult.succeed) {
return validationResult.value
}
const fieldPath = validationResult.fieldName || 'body'
const failingValue =
fieldPath === 'body'
? body
: getNestedValue(body, fieldPath.replace('body.', ''))
const errorField: {
message: string
value?: any
details: Array<ValidationErrorDetail>
} = {
message: validationResult.errorMessage,
details: validationResult.details ?? []
}
if (failingValue !== null && failingValue !== undefined) {
errorField.value = failingValue
}
throw new ValidateError(
{
[fieldPath]: errorField
},
validationResult.errorMessage
)
}
function getFromRef(
schema:
| OpenAPIV3.ReferenceObject
| OpenAPIV3.ArraySchemaObject
| OpenAPIV3.NonArraySchemaObject,
schemas: OpenAPIV3.ComponentsObject['schemas']
): OpenAPIV3.ArraySchemaObject | OpenAPIV3.NonArraySchemaObject {
if ('$ref' in schema) {
const schemaName =
schemas![schema.$ref.substr('#/components/schemas/'.length)]
if (typeof schemaName === 'undefined') {
throw new Error(`Schema '${schema.$ref}' not found`)
}
return getFromRef(schemaName, schemas)
}
return schema
}
function getNestedValue(obj: any, path: string): any {
const parts = path.split('.')
let current = obj
for (const part of parts) {
if (current == null || typeof current !== 'object') {
return undefined
}
// Handle array indices
if (/^\d+$/.test(part)) {
current = current[parseInt(part, 10)]
} else {
current = current[part]
}
}
return current
}
type SafeValidatedValue =
| {
succeed: false
value?: unknown
errorMessage: string
fieldName: string
details?: Array<ValidationErrorDetail>
}
| { succeed: true; value: unknown }
function validateAndParseValueAgainstSchema(
name: string,
value: unknown,
schema:
| OpenAPIV3.ReferenceObject
| OpenAPIV3.ArraySchemaObject
| OpenAPIV3.NonArraySchemaObject,
schemas: OpenAPIV3.ComponentsObject['schemas'],
parentType: 'allOf' | 'oneOf' | 'array' | 'object' | 'unknown',
logger: CustomLogger
): SafeValidatedValue {
const currentSchema = getFromRef(schema, schemas)
// Nullable
if (value === null) {
if (currentSchema.nullable) {
return { succeed: true, value: currentSchema.default }
}
return {
succeed: false,
errorMessage: `This property is not nullable`,
fieldName: name
}
}
// Strings
if (currentSchema.type === 'string') {
// Special case for date format
if (value instanceof Date && currentSchema.format === 'date-time') {
return { succeed: true, value }
}
// Special case for binary format
if (currentSchema.format === 'binary' && Buffer.isBuffer(value)) {
return { succeed: true, value }
}
if (typeof value !== 'string') {
return {
succeed: false,
errorMessage: `This property must be a string`,
fieldName: name
}
}
if (
typeof currentSchema.minLength !== 'undefined' &&
value.length < currentSchema.minLength
) {
return {
succeed: false,
errorMessage: `This property must have ${currentSchema.minLength} characters minimum`,
fieldName: name
}
}
if (
typeof currentSchema.maxLength !== 'undefined' &&
value.length > currentSchema.maxLength
) {
return {
succeed: false,
errorMessage: `This property can have ${currentSchema.maxLength} characters maximum`,
fieldName: name
}
}
if (currentSchema.enum && currentSchema.enum.includes(value) === false) {
return {
succeed: false,
errorMessage: `This property must be one of ${currentSchema.enum}`,
fieldName: name,
value
}
}
if (currentSchema.pattern) {
const patternResult = validateAndParsePattern(
name,
value,
currentSchema.pattern
)
if (!patternResult.succeed) {
return {
succeed: false,
errorMessage: patternResult.errorMessage,
fieldName: name
}
}
}
if (currentSchema.format) {
const formatResult = validateAndParseFormat(
name,
value,
currentSchema.format,
logger
)
if (!formatResult.succeed) {
return {
succeed: false,
errorMessage: formatResult.errorMessage,
fieldName: name
}
}
}
return { succeed: true, value }
}
// Numbers
if (currentSchema.type === 'number') {
// Note: in body we don't want to parseFloat() because fields should
// already be parsed. And we don't want to transform a field with type string | number
// into a number if it's a string in the body
const isInBody = name === 'body' || name.startsWith('body.')
const parsedValue = isInBody ? (value as number) : parseFloat(String(value))
if (isNaN(parsedValue)) {
return {
succeed: false,
errorMessage: 'This property must be a number',
fieldName: name
}
}
if (typeof currentSchema.minimum !== 'undefined') {
if (parsedValue < currentSchema.minimum) {
return {
succeed: false,
errorMessage: `This property must be >= ${currentSchema.minimum}`,
fieldName: name
}
}
}
if (typeof currentSchema.maximum !== 'undefined') {
if (parsedValue > currentSchema.maximum) {
return {
succeed: false,
errorMessage: `This property must be <= ${currentSchema.maximum}`,
fieldName: name
}
}
}
if (
currentSchema.enum &&
currentSchema.enum.includes(parsedValue) === false
) {
return {
succeed: false,
errorMessage: `This property must be one of ${currentSchema.enum}`,
fieldName: name,
value
}
}
return { succeed: true, value: parsedValue }
}
// Boolean
if (currentSchema.type === 'boolean') {
const parsedValue = String(value)
if (['0', '1', 'false', 'true'].includes(parsedValue) === false) {
return {
succeed: false,
errorMessage: 'This property must be a boolean',
fieldName: name
}
}
return {
succeed: true,
value: parsedValue === '1' || parsedValue === 'true'
}
}
// Array
if (currentSchema.type === 'array') {
if (!Array.isArray(value)) {
return {
succeed: false,
errorMessage: 'This property must be an array',
fieldName: name
}
}
if (
typeof currentSchema.minItems !== 'undefined' &&
value.length < currentSchema.minItems
) {
return {
succeed: false,
errorMessage: `This property must have ${currentSchema.minItems} items minimum`,
fieldName: name
}
}
if (
typeof currentSchema.maxItems !== 'undefined' &&
value.length > currentSchema.maxItems
) {
return {
succeed: false,
errorMessage: `This property can have ${currentSchema.maxItems} items maximum`,
fieldName: name
}
}
const values = value.map((item, i) =>
validateAndParseValueAgainstSchema(
`${name}.${i}`,
item,
currentSchema.items,
schemas,
'array',
logger
)
)
const everyItemIsGood = values.every(value => value.succeed)
const firstFailure = values.find(value => value.succeed === false)
return everyItemIsGood
? { succeed: true, value: values.map(({ value }) => value) }
: {
succeed: false,
errorMessage: firstFailure?.errorMessage ?? '',
fieldName: firstFailure?.fieldName ?? name
}
}
// Object
if (currentSchema.type === 'object') {
if (typeof value !== 'object' || Array.isArray(value) === true) {
return {
succeed: false,
errorMessage: 'This property must be an object',
fieldName: name
}
}
const filteredProperties: Record<string, unknown> = {}
const propertyNames = Object.keys(currentSchema.properties || {}).filter(
propName => {
// Ignore readOnly properties
const val = currentSchema.properties![propName]
return !('readOnly' in val) || val.readOnly !== true
}
)
for (const propName of propertyNames) {
const propValue = (value as Record<string, unknown>)[propName]
const isNotDefined = typeof propValue === 'undefined'
const propSchema = currentSchema.properties![propName]
const isAnyValue =
'$ref' in propSchema &&
propSchema.$ref === '#/components/schemas/AnyValue'
if (
currentSchema.required?.includes(propName) &&
isNotDefined === true &&
isAnyValue === false
) {
return {
succeed: false,
errorMessage: `Property ${propName} is required`,
fieldName: `${name}.${propName}`
}
}
if (isNotDefined === false) {
const validationResult = validateAndParseValueAgainstSchema(
`${name}.${propName}`,
propValue,
currentSchema.properties![propName],
schemas,
'unknown',
logger
)
if (!validationResult.succeed) {
return validationResult
}
filteredProperties[propName] = validationResult.value
} else {
const propertySchema = getFromRef(
currentSchema.properties![propName],
schemas
)
if (propertySchema.default) {
filteredProperties[propName] = propertySchema.default
}
}
}
// Check for additional properties
// Compare against schema property names (excluding readOnly) to identify additional keys
const additionalKeys = Object.keys(value).filter(
key => propertyNames.includes(key) === false
)
if (
parentType !== 'allOf' &&
(features?.enableThrowOnUnexpectedAdditionalData ||
features?.enableLogUnexpectedAdditionalData) &&
currentSchema.additionalProperties === false
) {
if (additionalKeys.length > 0) {
if (features.enableLogUnexpectedAdditionalData) {
logger.warn(
`Additional properties are not allowed. Found: ${additionalKeys.join(', ')}`
)
}
if (features.enableThrowOnUnexpectedAdditionalData) {
return {
succeed: false,
errorMessage: `Additional properties are not allowed. Found: ${additionalKeys.join(', ')}`,
fieldName: name
}
}
}
} else if (
features?.enableThrowOnUnexpectedAdditionalData &&
currentSchema.additionalProperties === true
) {
for (const propName of additionalKeys) {
const propValue = (value as Record<string, unknown>)[propName]
if (typeof propValue !== 'undefined') {
filteredProperties[propName] = propValue
}
}
} else if (
currentSchema.additionalProperties &&
typeof currentSchema.additionalProperties !== 'boolean'
) {
// additionalProperties is a schema object - validate against it
for (const propName of additionalKeys) {
const propValue = (value as Record<string, unknown>)[propName]
if (typeof propValue !== 'undefined') {
const validationResult = validateAndParseValueAgainstSchema(
`${name}.${propName}`,
propValue,
currentSchema.additionalProperties as any,
schemas,
'unknown',
logger
)
if (!validationResult.succeed) {
return validationResult
}
filteredProperties[propName] = validationResult.value
}
}
} else {
if (
parentType !== 'allOf' &&
(features?.enableThrowOnUnexpectedAdditionalData ||
features?.enableLogUnexpectedAdditionalData) &&
additionalKeys.length > 0
) {
if (features.enableLogUnexpectedAdditionalData) {
logger.warn(
`Additional properties are not allowed. Found: ${additionalKeys.join(', ')}`
)
}
if (features.enableThrowOnUnexpectedAdditionalData) {
return {
succeed: false,
errorMessage: `Additional properties are not allowed. Found: ${additionalKeys.join(', ')}`,
fieldName: name
}
}
}
}
return { succeed: true, value: filteredProperties }
}
// AllOf
if (currentSchema.allOf) {
// try to validate every allOf and merge their results
const schemasValues = currentSchema.allOf.map((schema, i) =>
validateAndParseValueAgainstSchema(
`${name}.${i}`,
value,
schema,
schemas,
'allOf',
logger
)
)
// Check for any failures first
const firstFailure = schemasValues.find(v => !v.succeed)
if (firstFailure) {
return firstFailure
}
if (schemasValues.length === 1) {
return schemasValues[0]
}
// All succeeded, merge values
const mergedValue = Object.assign(
{},
...schemasValues.map(v => v.value as Record<string, unknown>)
)
return { succeed: true, value: mergedValue }
}
// OneOf
if (currentSchema.oneOf) {
let matchingValue: unknown | undefined
const details: Array<ValidationErrorDetail> = []
currentSchema.oneOf.forEach((schema, i) => {
const validationResult = validateAndParseValueAgainstSchema(
`${name}.${i}`,
value,
schema,
schemas,
'oneOf',
logger
)
if (validationResult.succeed) {
// set as matching value if we haven't found one
if (typeof matchingValue === 'undefined') {
matchingValue = validationResult.value
return
}
// replace matched value if the new one have more keys
if (
typeof matchingValue === 'object' &&
matchingValue !== null &&
typeof validationResult.value === 'object' &&
validationResult.value !== null &&
Object.keys(validationResult.value).length >
Object.keys(matchingValue).length
) {
matchingValue = validationResult.value
}
} else {
details.push({
errorMessage: validationResult.errorMessage,
fieldName: validationResult.fieldName
})
}
})
if (typeof matchingValue === 'undefined') {
return {
succeed: false,
errorMessage: 'Found no matching schema for provided value',
fieldName: name,
details
}
}
return { succeed: true, value: matchingValue }
}
if ('$ref' in schema && schema?.$ref !== '#/components/schemas/AnyValue') {
logger.warn(
`Schema of ${name} is not yet supported, skipping value validation`
)
}
return { succeed: true, value }
}
function validateAndParseFormat(
name: string,
value: string,
format: string,
logger: CustomLogger
): SafeValidatedValue {
if (format === 'date' || format === 'date-time') {
const date = new Date(value)
if (String(date) === 'Invalid Date') {
return {
succeed: false,
errorMessage: 'This property must be a valid date',
fieldName: name
}
}
return { succeed: true, value: date }
}
logger.warn(
`Format '${format}' is not yet supported, value is returned without additionnal parsing`
)
return { succeed: true, value }
}
function validateAndParsePattern(
name: string,
value: string,
pattern: string
): SafeValidatedValue {
const regex = new RegExp(pattern)
if (!regex.test(value)) {
return {
succeed: false,
errorMessage: `This property must match the pattern: ${regex}`,
fieldName: name
}
}
return { succeed: true, value }
}