forked from apigee-127/swagger-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidators.js
More file actions
413 lines (366 loc) · 12.8 KB
/
Copy pathvalidators.js
File metadata and controls
413 lines (366 loc) · 12.8 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
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
var _ = {
each: require('lodash.foreach'),
isArray: require('lodash.isarray'),
isBoolean: require('lodash.isboolean'),
isNaN: require('lodash.isnan'),
isNull: require('lodash.isnull'),
isString: require('lodash.isstring'),
isUndefined: require('lodash.isundefined'),
union: require('lodash.union'),
uniq: require('lodash.uniq')
};
var helpers = require('./helpers');
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateRegExp = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateTimeRegExp = /^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/;
var throwInvalidParameter = function throwInvalidParameter (name, message) {
var err = new Error('Parameter (' + name + ') ' + message);
err.failedValidation = true;
throw err;
};
var isValidDate = function isValidDate (date) {
var day;
var matches;
var month;
if (!_.isString(date)) {
date = date.toString();
}
matches = dateRegExp.exec(date);
if (matches === null) {
return false;
}
day = matches[3];
month = matches[2];
if (month < '01' || month > '12' || day < '01' || day > '31') {
return false;
}
return true;
};
var isValidDateTime = function isValidDateTime (dateTime) {
var hour;
var date;
var time;
var matches;
var minute;
var parts;
var second;
if (!_.isString(dateTime)) {
dateTime = dateTime.toString();
}
parts = dateTime.toLowerCase().split('t');
date = parts[0];
time = parts.length > 1 ? parts[1] : undefined;
if (!isValidDate(date)) {
return false;
}
matches = dateTimeRegExp.exec(time);
if (matches === null) {
return false;
}
hour = matches[1];
minute = matches[2];
second = matches[3];
if (hour > '23' || minute > '59' || second > '59') {
return false;
}
return true;
};
/**
* Validates the request's content type (when necessary).
*
* @param {string[]} gConsumes - The valid consumes at the API scope
* @param {string[]} oConsumes - The valid consumes at the operation scope
* @param {object} req - The request
*
* @throws Error if the content type is invalid
*/
module.exports.validateContentType = function validateContentType (gConsumes, oConsumes, req) {
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
var contentType = req.headers['content-type'] || 'application/octet-stream';
var consumes = _.union(oConsumes, gConsumes);
// Get only the content type
contentType = contentType.split(';')[0];
// Validate content type (Only for POST/PUT per HTTP spec)
if (consumes.length > 0 && ['POST', 'PUT'].indexOf(req.method) !== -1 && consumes.indexOf(contentType) === -1) {
throw new Error('Invalid content type (' + contentType + '). These are valid: ' + consumes.join(', '));
}
};
/**
* Validates the request parameter's value against the allowable values (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string[]} allowed - The allowable values
*
* @throws Error if the value is not allowable
*/
module.exports.validateEnum = function validateEnum (name, val, allowed) {
if (!_.isUndefined(allowed) && !_.isUndefined(val) && allowed.indexOf(val) === -1) {
throwInvalidParameter(name, 'is not an allowable value (' + allowed.join(', ') + '): ' + val);
}
};
/**
* Validates the request parameter's value is less than the maximum (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} maximum - The maximum value
* @param {boolean} [exclusive=false] - Whether or not the value includes the maximum in its comparison
*
* @throws Error if the value is greater than the maximum
*/
module.exports.validateMaximum = function validateMaximum (name, val, maximum, type, exclusive) {
var testMax;
var testVal;
if (_.isUndefined(exclusive)) {
exclusive = false;
}
if (type === 'integer') {
testVal = parseInt(val, 10);
} else if (type === 'number') {
testVal = parseFloat(val);
}
if (!_.isUndefined(maximum)) {
testMax = parseFloat(maximum);
if (exclusive && testVal >= testMax) {
throwInvalidParameter(name, 'is greater than or equal to the configured maximum (' + maximum + '): ' + val);
} else if (testVal > testMax) {
throwInvalidParameter(name, 'is greater than the configured maximum (' + maximum + '): ' + val);
}
}
};
/**
* Validates the request parameter's array count is less than the maximum (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} maxItems - The maximum number of items
*
* @throws Error if the value contains more items than allowable
*/
module.exports.validateMaxItems = function validateMaxItems (name, val, maxItems) {
if (!_.isUndefined(maxItems) && val.length > maxItems) {
throwInvalidParameter(name, 'contains more items than allowed: ' + maxItems);
}
};
/**
* Validates the request parameter's length is less than the maximum (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} maxLength - The maximum length
*
* @throws Error if the value's length is greater than the maximum
*/
module.exports.validateMaxLength = function validateMaxLength (name, val, maxLength) {
if (!_.isUndefined(maxLength) && val.length > maxLength) {
throwInvalidParameter(name, 'is longer than allowed: ' + maxLength);
}
};
/**
* Validates the request parameter's array count is greater than the minimum (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} minimum - The minimum value
* @param {boolean} [exclusive=false] - Whether or not the value includes the minimum in its comparison
*
* @throws Error if the value is less than the minimum
*/
module.exports.validateMinimum = function validateMinimum (name, val, minimum, type, exclusive) {
var testMin;
var testVal;
if (_.isUndefined(exclusive)) {
exclusive = false;
}
if (type === 'integer') {
testVal = parseInt(val, 10);
} else if (type === 'number') {
testVal = parseFloat(val);
}
if (!_.isUndefined(minimum)) {
testMin = parseFloat(minimum);
if (exclusive && testVal <= testMin) {
throwInvalidParameter(name, 'is less than or equal to the configured minimum (' + minimum + '): ' + val);
} else if (testVal < testMin) {
throwInvalidParameter(name, 'is less than the configured minimum (' + minimum + '): ' + val);
}
}
};
/**
* Validates the request parameter's value contains fewer items than allowed (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} minItems - The minimum number of items
*
* @throws Error if the value contains fewer items than allowable
*/
module.exports.validateMinItems = function validateMinItems (name, val, minItems) {
if (!_.isUndefined(minItems) && val.length < minItems) {
throwInvalidParameter(name, 'contains fewer items than allowed: ' + minItems);
}
};
/**
* Validates the request parameter's length is greater than the minimum (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} minLength - The minimum length
*
* @throws Error if the value's length is less than the minimum
*/
module.exports.validateMinLength = function validateMinLength (name, val, minLength) {
if (!_.isUndefined(minLength) && val.length < minLength) {
throwInvalidParameter(name, 'is shorter than allowed: ' + minLength);
}
};
/**
* Validtes the request parameter against its model schema.
*
* @param {string} name - The parameter name
* @param {object} val - The parameter value
* @param {string} version - The Swagger version
* @param {object} apiDOrSO - The Swagger API Declaration (1.2) or Swagger Object (2.0)
* @param {string} modelIdOrPath - The model id or path
*
* @throws Error if the value is not a valid model
*/
module.exports.validateModel = function validateModel (name, val, version, apiDOrSO, modelIdOrPath) {
var spec = helpers.getSpec(version);
var validate = function validate (data) {
var result = spec.validateModel(apiDOrSO, modelIdOrPath, data);
if (!_.isUndefined(result)) {
try {
throwInvalidParameter(name, 'is not a valid ' + modelIdOrPath + ' model');
} catch (err) {
err.errors = result.errors;
throw err;
}
}
};
if (_.isArray(val)) {
_.each(val, function (item) {
validate(item);
});
} else {
validate(val);
}
};
/**
* Validates the request parameter's matches a pattern (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} pattern - The pattern
*
* @throws Error if the value does not match the pattern
*/
module.exports.validatePattern = function validatePattern (name, val, pattern) {
if (!_.isUndefined(pattern) && _.isNull(val.match(new RegExp(pattern)))) {
throwInvalidParameter(name, 'does not match required pattern: ' + pattern);
}
};
/**
* Validates the request parameter's requiredness (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {boolean} required - Whether or not the parameter is required
*
* @throws Error if the value is required but is not present
*/
module.exports.validateRequiredness = function validateRequiredness (name, val, required) {
if (!_.isUndefined(required) && required === true && _.isUndefined(val)) {
throwInvalidParameter(name, 'is required');
}
};
/**
* Validates the request parameter's type and format (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} type - The parameter type
* @param {string} format - The parameter format
* @param {boolean} [skipError=false] - Whether or not to skip throwing an error (Useful for validating arrays)
*
* @throws Error if the value is not the proper type or format
*/
module.exports.validateTypeAndFormat = function validateTypeAndFormat (name, val, type, format, skipError) {
var result = true;
if (_.isArray(val)) {
_.each(val, function (aVal, index) {
if (!validateTypeAndFormat(name, aVal, type, format, true)) {
throwInvalidParameter(name, 'at index ' + index + ' is not a valid ' + type + ': ' + aVal);
}
});
} else {
switch (type) {
case 'boolean':
result = _.isBoolean(val) || ['false', 'true'].indexOf(val) !== -1;
break;
case 'integer':
result = !_.isNaN(parseInt(val, 10));
break;
case 'number':
result = !_.isNaN(parseFloat(val));
break;
case 'string':
if (!_.isUndefined(format)) {
switch (format) {
case 'date':
result = isValidDate(val);
break;
case 'date-time':
result = isValidDateTime(val);
break;
}
}
break;
}
}
if (skipError) {
return result;
} else if (!result) {
throwInvalidParameter(name, 'is not a valid ' + (_.isUndefined(format) ? '' : format + ' ') + type + ': ' + val);
}
};
/**
* Validates the request parameter's values are unique (when necessary).
*
* @param {string} name - The parameter name
* @param {string[]} val - The parameter value
* @param {boolean} isUnique - Whether or not the parameter values are unique
*
* @throws Error if the value has duplicates
*/
module.exports.validateUniqueItems = function validateUniqueItems (name, val, isUnique) {
if (!_.isUndefined(isUnique) && _.uniq(val).length !== val.length) {
throwInvalidParameter(name, 'does not allow duplicate values: ' + val.join(', '));
}
};