This repository has been archived by the owner on Nov 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathvalidateBody.js
234 lines (202 loc) · 5.72 KB
/
validateBody.js
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
const jph = require('json-parse-helpfulerror');
const mediaTyper = require('media-typer');
const contentTypeUtils = require('content-type');
const { TextDiff } = require('../../../lib/validators/text-diff');
const { JsonExample } = require('../../../lib/validators/json-example');
const { JsonSchema } = require('../../../lib/validators/json-schema');
function isPlainText(mediaType) {
return mediaType.type === 'text' && mediaType.subtype === 'plain';
}
function isJson(mediaType) {
if (!mediaType) {
return false;
}
return (
(mediaType.type === 'application' && mediaType.subtype === 'json') ||
mediaType.suffix === 'json'
);
}
function isJsonSchema(mediaType) {
if (!mediaType) {
return false;
}
return (
mediaType.type === 'application' &&
mediaType.subtype === 'schema' &&
mediaType.suffix === 'json'
);
}
/**
* Parses a given content-type header into media type.
* @param {string} contentType
* @returns {[Error, MediaType]}
*/
function parseContentType(contentType) {
try {
const { type } = contentTypeUtils.parse(`${contentType}`);
return mediaTyper.parse(type);
} catch (error) {
return null;
}
}
/**
* Determines if a given 'Content-Type' header contains JSON.
* @param {string} contentType
* @returns {boolean}
*/
function isJsonContentType(contentType) {
const mediaType = parseContentType(contentType);
return mediaType ? isJson(mediaType) : false;
}
/**
* Returns a tuple of error and body media type based
* on the given body and normalized headers.
* @param {string} body
* @param {Object} headers
* @param {'real'|'expected'} bodyType
* @returns {[error, bodyType]}
*/
function getBodyType(body, contentType, httpMessageOrigin) {
const hasJsonContentType = isJsonContentType(contentType);
try {
jph.parse(body);
const bodyMediaType = parseContentType(
hasJsonContentType ? contentType : 'application/json'
);
return [null, bodyMediaType];
} catch (parsingError) {
const fallbackMediaType = mediaTyper.parse('text/plain');
const error = hasJsonContentType
? `Can't validate: ${httpMessageOrigin} body 'Content-Type' header is '${contentType}' \
but body is not a parseable JSON:
${parsingError.message}`
: null;
return [error, fallbackMediaType];
}
}
/**
* Returns a tuple of error and schema media type
* based on given body schema.
* @param {string} bodySchema
* @returns {[error, schemaType]}
*/
function getBodySchemaType(bodySchema) {
const jsonSchemaType = mediaTyper.parse('application/schema+json');
if (typeof bodySchema !== 'string') {
return [null, jsonSchemaType];
}
try {
jph.parse(bodySchema);
return [null, jsonSchemaType];
} catch (exception) {
const error = `Can't validate: expected body JSON Schema is not a parseable JSON:\n${
exception.message
}`;
return [error, null];
}
}
/**
* Returns a body validator class based on the given
* real and expected body media types.
* @param {MediaType} realType
* @param {MediaType} expectedType
* @returns {Validator}
*/
function getBodyValidator(realType, expectedType) {
const both = (predicate) => (real, expected) => {
return [real, expected].every(predicate);
};
const validators = [
[TextDiff, both(isPlainText)],
// List JsonSchema first, because weak predicate of JsonExample
// would resolve on "application/schema+json" media type too.
[
JsonSchema,
(real, expected) => {
return isJson(real) && isJsonSchema(expected);
}
],
[JsonExample, both(isJson)]
];
const validator = validators.find(([_name, predicate]) => {
return predicate(realType, expectedType);
});
return [null, validator[0]];
}
/**
* Validates given bodies of transaction elements.
* @param {Object} real
* @param {Object} expected
*/
function validateBody(real, expected) {
const results = [];
const bodyType = typeof real.body;
if (bodyType !== 'string') {
throw new Error(`Expected HTTP body to be a String, but got: ${bodyType}`);
}
const [realTypeError, realType] = getBodyType(
real.body,
real.headers && real.headers['content-type'],
'real'
);
const [expectedTypeError, expectedType] = expected.bodySchema
? getBodySchemaType(expected.bodySchema)
: getBodyType(
expected.body,
expected.headers && expected.headers['content-type'],
'expected'
);
if (realTypeError) {
results.push({
message: realTypeError,
severity: 'error'
});
}
if (expectedTypeError) {
results.push({
message: expectedTypeError,
severity: 'error'
});
}
const hasErrors = results.some((result) =>
['error'].includes(result.severity)
);
// Skipping body validation in case errors during
// real/expected body type definition.
const [validatorError, ValidatorClass] = hasErrors
? [null, null]
: getBodyValidator(realType, expectedType);
if (validatorError) {
results.push({
message: validatorError,
severity: 'error'
});
}
const usesJsonSchema = ValidatorClass && ValidatorClass.name === 'JsonSchema';
const validator =
ValidatorClass &&
new ValidatorClass(
real.body,
usesJsonSchema ? expected.bodySchema : expected.body
);
const rawData = validator && validator.validate();
const validatorResults = validator ? validator.evaluateOutputToResults() : [];
results.push(...validatorResults);
return {
validator: ValidatorClass && ValidatorClass.name,
realType: mediaTyper.format(realType),
expectedType: mediaTyper.format(expectedType),
rawData,
results
};
}
module.exports = {
validateBody,
isJson,
isJsonSchema,
isJsonContentType,
parseContentType,
getBodyType,
getBodySchemaType,
getBodyValidator
};