This repository has been archived by the owner on Aug 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 370
/
specs.js
1518 lines (1246 loc) · 50.9 KB
/
specs.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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 _ = require('lodash');
var async = require('async');
var helpers = require('./helpers');
var JsonRefs = require('json-refs');
var SparkMD5 = require('spark-md5');
var swaggerConverter = require('swagger-converter');
var traverse = require('traverse');
var validators = require('./validators');
var YAML = require('js-yaml');
// Work around swagger-converter packaging issue (Browser builds only)
if (_.isPlainObject(swaggerConverter)) {
swaggerConverter = global.SwaggerConverter.convert;
}
var documentCache = {};
var sanitizeRef = function (version, ref) {
return version !== '1.2' ? ref : ref.replace('#/models/', '');
};
var swagger1RefPreProcesor = function (obj) {
var pObj = _.cloneDeep(obj);
pObj.$ref = '#/models/' + obj.$ref;
return pObj;
};
var validOptionNames = _.map(helpers.swaggerOperationMethods, function (method) {
return method.toLowerCase();
});
var isRemotePtr = function (refDetails) {
return ['relative', 'remote'].indexOf(refDetails.type) > -1;
};
var createErrorOrWarning = function (code, message, path, dest) {
dest.push({
code: code,
message: message,
path: path
});
};
var addReference = function (cacheEntry, defPathOrPtr, refPathOrPtr, results, omitError) {
var result = true;
var swaggerVersion = helpers.getSwaggerVersion(cacheEntry.resolved);
var defPath = _.isArray(defPathOrPtr) ? defPathOrPtr : JsonRefs.pathFromPtr(defPathOrPtr);
var defPtr = _.isArray(defPathOrPtr) ? JsonRefs.pathToPtr(defPathOrPtr) : defPathOrPtr;
var refPath = _.isArray(refPathOrPtr) ? refPathOrPtr : JsonRefs.pathFromPtr(refPathOrPtr);
var refPtr = _.isArray(refPathOrPtr) ? JsonRefs.pathToPtr(refPathOrPtr) : refPathOrPtr;
var code;
var def;
var displayId;
var i;
var msgPrefix;
var type;
def = cacheEntry.definitions[defPtr];
type = defPath[0];
code = type === 'securityDefinitions' ?
'SECURITY_DEFINITION' :
type.substring(0, type.length - 1).toUpperCase();
displayId = swaggerVersion === '1.2' ? defPath[defPath.length - 1] : defPtr;
msgPrefix = type === 'securityDefinitions' ?
'Security definition' :
code.charAt(0) + code.substring(1).toLowerCase();
// This is an authorization scope reference
if (['authorizations', 'securityDefinitions'].indexOf(defPath[0]) > -1 && defPath[2] === 'scopes') {
code += '_SCOPE';
msgPrefix += ' scope';
}
// If the reference was not found and this is not an authorization/security scope reference, attempt to find a
// parent object to add the reference too. (Issue 176)
if (_.isUndefined(def) && ['AUTHORIZATION_SCOPE', 'SECURITY_DEFINITION_SCOPE'].indexOf(code) === -1) {
// Attempt to find the definition in case the reference is to a path within a definition`
for (i = 1; i < defPath.length; i++) {
var pPath = defPath.slice(0, defPath.length - i);
var pPtr = JsonRefs.pathToPtr(pPath);
var pDef = cacheEntry.definitions[pPtr];
if (!_.isUndefined(pDef)) {
def = pDef;
break;
}
}
}
if (_.isUndefined(def)) {
if (!omitError) {
if (cacheEntry.swaggerVersion !== '1.2' && ['SECURITY_DEFINITION', 'SECURITY_DEFINITION_SCOPE'].indexOf(code) === -1) {
refPath.push('$ref');
}
createErrorOrWarning('UNRESOLVABLE_' + code, msgPrefix + ' could not be resolved: ' + displayId, refPath,
results.errors);
}
result = false;
} else {
if (_.isUndefined(def.references)) {
def.references = [];
}
def.references.push(refPtr);
}
return result;
};
var getOrComposeSchema = function (documentMetadata, modelId) {
var title = 'Composed ' + (documentMetadata.swaggerVersion === '1.2' ?
JsonRefs.pathFromPtr(modelId).pop() :
modelId);
var metadata = documentMetadata.definitions[modelId];
var originalT = traverse(documentMetadata.original);
var resolvedT = traverse(documentMetadata.resolved);
var composed;
var original;
if (!metadata) {
return undefined;
}
original = _.cloneDeep(originalT.get(JsonRefs.pathFromPtr(modelId)));
composed = _.cloneDeep(resolvedT.get(JsonRefs.pathFromPtr(modelId)));
// Convert the Swagger 1.2 document to a valid JSON Schema file
if (documentMetadata.swaggerVersion === '1.2') {
// Create inheritance model
if (metadata.lineage.length > 0) {
composed.allOf = [];
_.each(metadata.lineage, function (modelId) {
composed.allOf.push(getOrComposeSchema(documentMetadata, modelId));
});
}
// Remove the subTypes property
delete composed.subTypes;
_.each(composed.properties, function (property, name) {
var oProp = original.properties[name];
// Convert the string values to numerical values
_.each(['maximum', 'minimum'], function (prop) {
if (_.isString(property[prop])) {
property[prop] = parseFloat(property[prop]);
}
});
_.each(JsonRefs.findRefs(oProp, {
includeInvalid: true,
refPreProcessor: swagger1RefPreProcesor
}), function (refDetails, refPtr) {
var dMetadata = documentMetadata.definitions[refDetails.uri];
var path = JsonRefs.pathFromPtr(refPtr);
if (dMetadata.lineage.length > 0) {
traverse(property).set(path, getOrComposeSchema(documentMetadata, refDetails.uri));
} else {
traverse(property).set(path.concat('title'), 'Composed ' + sanitizeRef(documentMetadata.swaggerVersion,
refDetails.uri));
}
});
});
}
// Scrub id properties
composed = traverse(composed).map(function (val) {
if (this.key === 'id' && _.isString(val)) {
this.remove();
}
});
composed.title = title;
return composed;
};
var createUnusedErrorOrWarning = function (val, codeSuffix, msgPrefix, path, dest) {
createErrorOrWarning('UNUSED_' + codeSuffix, msgPrefix + ' is defined but is not used: ' + val, path, dest);
};
var getDocumentCache = function (apiDOrSO) {
var key = SparkMD5.hash(JSON.stringify(apiDOrSO));
var cacheEntry = documentCache[key] || _.find(documentCache, function (cacheEntry) {
return cacheEntry.resolvedId === key;
});
if (!cacheEntry) {
cacheEntry = documentCache[key] = {
definitions: {},
original: apiDOrSO,
resolved: undefined,
swaggerVersion: helpers.getSwaggerVersion(apiDOrSO)
};
}
return cacheEntry;
};
var handleValidationError = function (results, callback) {
var err = new Error('The Swagger document(s) are invalid');
err.errors = results.errors;
err.failedValidation = true;
err.warnings = results.warnings;
if (results.apiDeclarations) {
err.apiDeclarations = results.apiDeclarations;
}
callback(err);
};
var normalizePath = function (path) {
var matches = path.match(/\{(.*?)\}/g);
var argNames = [];
var normPath = path;
if (matches) {
_.each(matches, function (match, index) {
normPath = normPath.replace(match, '{' + index + '}');
argNames.push(match.replace(/[{}]/g, ''));
});
}
return {
path: normPath,
args: argNames
};
};
var removeCirculars = function (obj) {
function walk (ancestors, node, path) {
function walkItem (item, segment) {
path.push(segment);
walk(ancestors, item, path);
path.pop();
}
// We do not process circular objects again
if (ancestors.indexOf(node) === -1) {
ancestors.push(node);
if (_.isArray(node)) {
_.each(node, function (member, index) {
walkItem(member, index.toString());
});
} else if (_.isPlainObject(node)) {
_.forOwn(node, function (member, key) {
walkItem(member, key.toString());
});
}
} else {
_.set(obj, path, {});
}
ancestors.pop();
}
walk([], obj, []);
};
var validateNoExist = function (data, val, codeSuffix, msgPrefix, path, dest) {
if (!_.isUndefined(data) && data.indexOf(val) > -1) {
createErrorOrWarning('DUPLICATE_' + codeSuffix, msgPrefix + ' already defined: ' + val, path, dest);
}
};
var validateSchemaConstraints = function (documentMetadata, schema, path, results, skip) {
try {
validators.validateSchemaConstraints(documentMetadata.swaggerVersion, schema, path, undefined);
} catch (err) {
if (!skip) {
createErrorOrWarning(err.code, err.message, err.path, results.errors);
}
}
};
var processDocument = function (documentMetadata, results) {
var swaggerVersion = documentMetadata.swaggerVersion;
var getDefinitionMetadata = function (defPath, inline) {
var defPtr = JsonRefs.pathToPtr(defPath);
var metadata = documentMetadata.definitions[defPtr];
if (!metadata) {
metadata = documentMetadata.definitions[defPtr] = {
inline: inline || false,
references: []
};
// For model definitions, add the inheritance properties
if (['definitions', 'models'].indexOf(JsonRefs.pathFromPtr(defPtr)[0]) > -1) {
metadata.cyclical = false;
metadata.lineage = undefined;
metadata.parents = [];
}
}
return metadata;
};
var getDisplayId = function (id) {
return swaggerVersion === '1.2' ? JsonRefs.pathFromPtr(id).pop() : id;
};
var jsonRefsOptions = {
filter: 'local',
includeInvalid: true
};
var walk = function (root, id, lineage) {
var definition = documentMetadata.definitions[id || root];
if (definition) {
_.each(definition.parents, function (parent) {
lineage.push(parent);
if (root !== parent) {
walk(root, parent, lineage);
}
});
}
};
var authDefsProp = swaggerVersion === '1.2' ? 'authorizations' : 'securityDefinitions';
var modelDefsProp = swaggerVersion === '1.2' ? 'models' : 'definitions';
// Process authorization definitions
_.each(documentMetadata.resolved[authDefsProp], function (authorization, name) {
var securityDefPath = [authDefsProp, name];
// Swagger 1.2 only has authorization definitions in the Resource Listing
if (swaggerVersion === '1.2' && !authorization.type) {
return;
}
// Create the authorization definition metadata
getDefinitionMetadata(securityDefPath);
_.reduce(authorization.scopes, function (seenScopes, scope, indexOrName) {
var scopeName = swaggerVersion === '1.2' ? scope.scope : indexOrName;
var scopeDefPath = securityDefPath.concat(['scopes', indexOrName.toString()]);
var scopeMetadata = getDefinitionMetadata(securityDefPath.concat(['scopes', scopeName]));
scopeMetadata.scopePath = scopeDefPath;
// Identify duplicate authorization scope defined in the Resource Listing
validateNoExist(seenScopes, scopeName, 'AUTHORIZATION_SCOPE_DEFINITION', 'Authorization scope definition',
swaggerVersion === '1.2' ? scopeDefPath.concat('scope') : scopeDefPath, results.warnings);
seenScopes.push(scopeName);
return seenScopes;
}, []);
});
// Process model definitions
_.each(documentMetadata.resolved[modelDefsProp], function (model, modelId) {
var modelDefPath = [modelDefsProp, modelId];
var modelMetadata = getDefinitionMetadata(modelDefPath);
// Identify model id mismatch (Id in models object is not the same as the model's id in the models object)
if (swaggerVersion === '1.2' && modelId !== model.id) {
createErrorOrWarning('MODEL_ID_MISMATCH', 'Model id does not match id in models object: ' + model.id,
modelDefPath.concat('id'), results.errors);
}
// Do not reprocess parents/references if already processed
if (_.isUndefined(modelMetadata.lineage)) {
// Handle inheritance references
switch (swaggerVersion) {
case '1.2':
_.each(model.subTypes, function (subType, index) {
var subPath = ['models', subType];
var subPtr = JsonRefs.pathToPtr(subPath);
var subMetadata = documentMetadata.definitions[subPtr];
var refPath = modelDefPath.concat(['subTypes', index.toString()]);
// If the metadata does not yet exist, create it
if (!subMetadata && documentMetadata.resolved[modelDefsProp][subType]) {
subMetadata = getDefinitionMetadata(subPath);
}
// If the reference is valid, add the parent
if (addReference(documentMetadata, subPath, refPath, results)) {
subMetadata.parents.push(JsonRefs.pathToPtr(modelDefPath));
}
});
break;
default:
_.each(documentMetadata.original[modelDefsProp][modelId].allOf, function (schema, index) {
var isInline = false;
var parentPath;
if (_.isUndefined(schema.$ref) || isRemotePtr(JsonRefs.getRefDetails(schema))) {
isInline = true;
parentPath = modelDefPath.concat(['allOf', index.toString()]);
} else {
parentPath = JsonRefs.pathFromPtr(schema.$ref);
}
// If the parent model does not exist, do not create its metadata
if (!_.isUndefined(traverse(documentMetadata.resolved).get(parentPath))) {
// Create metadata for parent
getDefinitionMetadata(parentPath, isInline);
modelMetadata.parents.push(JsonRefs.pathToPtr(parentPath));
}
});
break;
}
}
});
switch (swaggerVersion) {
case '2.0':
// Process parameter definitions
_.each(documentMetadata.resolved.parameters, function (parameter, name) {
var path = ['parameters', name];
getDefinitionMetadata(path);
validateSchemaConstraints(documentMetadata, parameter, path, results);
});
// Process response definitions
_.each(documentMetadata.resolved.responses, function (response, name) {
var path = ['responses', name];
getDefinitionMetadata(path);
validateSchemaConstraints(documentMetadata, response, path, results);
});
break;
}
// Validate definition/models (Inheritance, property definitions, ...)
_.each(documentMetadata.definitions, function (metadata, id) {
var defPath = JsonRefs.pathFromPtr(id);
var definition = traverse(documentMetadata.original).get(defPath);
var defProp = defPath[0];
var code = defProp.substring(0, defProp.length - 1).toUpperCase();
var msgPrefix = code.charAt(0) + code.substring(1).toLowerCase();
var dProperties;
var iProperties;
var lineage;
// The only checks we perform below are inheritance checks so skip all non-model definitions
if (['definitions', 'models'].indexOf(defProp) === -1) {
return;
}
dProperties = [];
iProperties = [];
lineage = metadata.lineage;
// Do not reprocess lineage if already processed
if (_.isUndefined(lineage)) {
lineage = [];
walk(id, undefined, lineage);
// Root > next > ...
lineage.reverse();
metadata.lineage = _.cloneDeep(lineage);
metadata.cyclical = lineage.length > 1 && lineage[0] === id;
}
// Swagger 1.2 does not allow multiple inheritance while Swagger 2.0+ does
if (metadata.parents.length > 1 && swaggerVersion === '1.2') {
createErrorOrWarning('MULTIPLE_' + code + '_INHERITANCE',
'Child ' + code.toLowerCase() + ' is sub type of multiple models: ' +
_.map(metadata.parents, function (parent) {
return getDisplayId(parent);
}).join(' && '), defPath, results.errors);
}
if (metadata.cyclical) {
createErrorOrWarning('CYCLICAL_' + code + '_INHERITANCE',
msgPrefix + ' has a circular inheritance: ' +
_.map(lineage, function (dep) {
return getDisplayId(dep);
}).join(' -> ') + ' -> ' + getDisplayId(id),
defPath.concat(swaggerVersion === '1.2' ? 'subTypes' : 'allOf'), results.errors);
}
// Remove self reference from the end of the lineage (Front too if cyclical)
_.each(lineage.slice(metadata.cyclical ? 1 : 0), function (id) {
var pModel = traverse(documentMetadata.resolved).get(JsonRefs.pathFromPtr(id));
_.each(Object.keys(pModel.properties || {}), function (name) {
if (iProperties.indexOf(name) === -1) {
iProperties.push(name);
}
});
});
// Validate simple definitions
validateSchemaConstraints(documentMetadata, definition, defPath, results);
// Identify redeclared properties
_.each(definition.properties, function (property, name) {
var pPath = defPath.concat(['properties', name]);
// Do not process unresolved properties
if (!_.isUndefined(property)) {
validateSchemaConstraints(documentMetadata, property, pPath, results);
if (iProperties.indexOf(name) > -1) {
createErrorOrWarning('CHILD_' + code + '_REDECLARES_PROPERTY',
'Child ' + code.toLowerCase() + ' declares property already declared by ancestor: ' +
name,
pPath, results.errors);
} else {
dProperties.push(name);
}
}
});
// Identify missing required properties
_.each(definition.required || [], function (name, index) {
var type = swaggerVersion === '1.2' ? 'Model' : 'Definition';
if (iProperties.indexOf(name) === -1 && dProperties.indexOf(name) === -1) {
createErrorOrWarning('MISSING_REQUIRED_' + type.toUpperCase() + '_PROPERTY',
type + ' requires property but it is not defined: ' + name,
defPath.concat(['required', index.toString()]), results.errors);
}
});
});
if (documentMetadata.swaggerVersion === '1.2') {
jsonRefsOptions.refPreProcessor = swagger1RefPreProcesor;
}
// Process local references
_.each(JsonRefs.findRefs(documentMetadata.original, jsonRefsOptions), function (refDetails, refPtr) {
addReference(documentMetadata, refDetails.uri, refPtr, results);
});
// Process invalid references
_.each(documentMetadata.referencesMetadata, function (refDetails, refPtr) {
if (isRemotePtr(refDetails) && refDetails.missing === true) {
results.errors.push({
code: 'UNRESOLVABLE_REFERENCE',
message: 'Reference could not be resolved: ' + sanitizeRef(documentMetadata.swaggerVersion, refDetails.uri),
path: JsonRefs.pathFromPtr(refPtr).concat('$ref')
});
}
});
};
var validateExist = function (data, val, codeSuffix, msgPrefix, path, dest) {
if (!_.isUndefined(data) && data.indexOf(val) === -1) {
createErrorOrWarning('UNRESOLVABLE_' + codeSuffix, msgPrefix + ' could not be resolved: ' + val, path, dest);
}
};
var processAuthRefs = function (documentMetadata, authRefs, path, results) {
var code = documentMetadata.swaggerVersion === '1.2' ? 'AUTHORIZATION' : 'SECURITY_DEFINITION';
var msgPrefix = code === 'AUTHORIZATION' ? 'Authorization' : 'Security definition';
if (documentMetadata.swaggerVersion === '1.2') {
_.reduce(authRefs, function (seenNames, scopes, name) {
var authPtr = ['authorizations', name];
var aPath = path.concat([name]);
// Add reference or record unresolved authorization
if (addReference(documentMetadata, authPtr, aPath, results)) {
_.reduce(scopes, function (seenScopes, scope, index) {
var sPath = aPath.concat(index.toString(), 'scope');
var sPtr = authPtr.concat(['scopes', scope.scope]);
validateNoExist(seenScopes, scope.scope, code + '_SCOPE_REFERENCE', msgPrefix + ' scope reference', sPath,
results.warnings);
// Add reference or record unresolved authorization scope
addReference(documentMetadata, sPtr, sPath, results);
return seenScopes.concat(scope.scope);
}, []);
}
return seenNames.concat(name);
}, []);
} else {
_.reduce(authRefs, function (seenNames, scopes, index) {
_.each(scopes, function (scopes, name) {
var authPtr = ['securityDefinitions', name];
var authRefPath = path.concat(index.toString(), name);
// Ensure the security definition isn't referenced more than once (Swagger 2.0+)
validateNoExist(seenNames, name, code + '_REFERENCE', msgPrefix + ' reference', authRefPath,
results.warnings);
seenNames.push(name);
// Add reference or record unresolved authorization
if (addReference(documentMetadata, authPtr, authRefPath, results)) {
_.each(scopes, function (scope, index) {
// Add reference or record unresolved authorization scope
var sPtr = authPtr.concat(['scopes', scope]);
addReference(documentMetadata, sPtr, authRefPath.concat(index.toString()),
results);
});
}
});
return seenNames;
}, []);
}
};
var resolveRefs = function (apiDOrSO, callback) {
var cacheEntry = getDocumentCache(apiDOrSO);
var swaggerVersion = helpers.getSwaggerVersion(apiDOrSO);
var jsonRefsOptions = {
includeInvalid: true,
loaderOptions: {
processContent: function (res, callback) {
callback(undefined, YAML.safeLoad(res.text));
}
}
};
if (!cacheEntry.resolved) {
// For Swagger 1.2, we have to create real JSON References
if (swaggerVersion === '1.2') {
jsonRefsOptions.refPreProcessor = swagger1RefPreProcesor;
}
// Resolve references
JsonRefs.resolveRefs(apiDOrSO, jsonRefsOptions)
.then(function (results) {
removeCirculars(results.resolved);
// Fix circular references
_.each(results.refs, function (refDetails, refPtr) {
if (refDetails.circular) {
_.set(results.resolved, JsonRefs.pathFromPtr(refPtr), {});
}
});
cacheEntry.referencesMetadata = results.refs;
cacheEntry.resolved = results.resolved;
cacheEntry.resolvedId = SparkMD5.hash(JSON.stringify(results.resolved));
callback();
})
.catch(callback);
} else {
callback();
}
};
var validateAgainstSchema = function (spec, schemaOrName, data, callback) {
var validator = _.isString(schemaOrName) ? spec.validators[schemaOrName] : helpers.createJsonValidator();
helpers.registerCustomFormats(data);
try {
validators.validateAgainstSchema(schemaOrName, data, validator);
} catch (err) {
if (err.failedValidation) {
return callback(undefined, err.results);
} else {
return callback(err);
}
}
resolveRefs(data, function (err) {
return callback(err);
});
};
var validateDefinitions = function (documentMetadata, results) {
// Validate unused definitions
_.each(documentMetadata.definitions, function (metadata, id) {
var defPath = JsonRefs.pathFromPtr(id);
var defType = defPath[0].substring(0, defPath[0].length - 1);
var displayId = documentMetadata.swaggerVersion === '1.2' ? defPath[defPath.length - 1] : id;
var code = defType === 'securityDefinition' ? 'SECURITY_DEFINITION' : defType.toUpperCase();
var msgPrefix = defType === 'securityDefinition' ?
'Security definition' :
defType.charAt(0).toUpperCase() + defType.substring(1);
if (metadata.references.length === 0 && !metadata.inline) {
// Swagger 1.2 authorization scope
if (metadata.scopePath) {
code += '_SCOPE';
msgPrefix += ' scope';
defPath = metadata.scopePath;
}
createUnusedErrorOrWarning(displayId, code, msgPrefix, defPath, results.warnings);
}
});
};
var validateParameters = function (spec, documentMetadata, nPath, parameters, path, results,
skipMissing) {
var createParameterComboError = function (path) {
createErrorOrWarning('INVALID_PARAMETER_COMBINATION',
'API cannot have a a body parameter and a ' +
(spec.version === '1.2' ? 'form' : 'formData') + ' parameter',
path, results.errors);
};
var pathParams = [];
var seenBodyParam = false;
var seenFormParam = false;
_.reduce(parameters, function (seenParameters, parameter, index) {
var pPath = path.concat(['parameters', index.toString()]);
// Unresolved parameter
if (_.isUndefined(parameter)) {
return;
}
// Identify duplicate parameter names
validateNoExist(seenParameters, parameter.name, 'PARAMETER', 'Parameter', pPath.concat('name'),
results.errors);
// Keep track of body and path parameters
if (parameter.paramType === 'body' || parameter.in === 'body') {
if (seenBodyParam === true) {
createErrorOrWarning('DUPLICATE_API_BODY_PARAMETER', 'API has more than one body parameter', pPath,
results.errors);
} else if (seenFormParam === true) {
createParameterComboError(pPath);
}
seenBodyParam = true;
} else if (parameter.paramType === 'form' || parameter.in === 'formData') {
if (seenBodyParam === true) {
createParameterComboError(pPath);
}
seenFormParam = true;
} else if (parameter.paramType === 'path' || parameter.in === 'path') {
if (nPath.args.indexOf(parameter.name) === -1) {
createErrorOrWarning('UNRESOLVABLE_API_PATH_PARAMETER',
'API path parameter could not be resolved: ' + parameter.name, pPath.concat('name'),
results.errors);
}
pathParams.push(parameter.name);
}
if (spec.primitives.indexOf(parameter.type) === -1 && spec.version === '1.2') {
addReference(documentMetadata, '#/models/' + parameter.type, pPath.concat('type'), results);
}
// Validate parameter constraints
validateSchemaConstraints(documentMetadata, parameter, pPath, results, parameter.skipErrors);
return seenParameters.concat(parameter.name);
}, []);
// Validate missing path parameters (in path but not in operation.parameters)
if (_.isUndefined(skipMissing) || skipMissing === false) {
_.each(_.difference(nPath.args, pathParams), function (unused) {
createErrorOrWarning('MISSING_API_PATH_PARAMETER', 'API requires path parameter but it is not defined: ' + unused,
documentMetadata.swaggerVersion === '1.2' ? path.slice(0, 2).concat('path') : path,
results.errors);
});
}
};
var validateSwagger1_2 = function (spec, resourceListing, apiDeclarations, callback) { // jshint ignore:line
var adResourcePaths = [];
var rlDocumentMetadata = getDocumentCache(resourceListing);
var rlResourcePaths = [];
var results = {
errors: [],
warnings: [],
apiDeclarations: []
};
// Process Resource Listing resource definitions
rlResourcePaths = _.reduce(resourceListing.apis, function (seenPaths, api, index) {
// Identify duplicate resource paths defined in the Resource Listing
validateNoExist(seenPaths, api.path, 'RESOURCE_PATH', 'Resource path', ['apis', index.toString(), 'path'],
results.errors);
seenPaths.push(api.path);
return seenPaths;
}, []);
// Process Resource Listing definitions (authorizations)
processDocument(rlDocumentMetadata, results);
// Process each API Declaration
adResourcePaths = _.reduce(apiDeclarations, function (seenResourcePaths, apiDeclaration, index) {
var aResults = results.apiDeclarations[index] = {
errors: [],
warnings: []
};
var adDocumentMetadata = getDocumentCache(apiDeclaration);
// Identify duplicate resource paths defined in the API Declarations
validateNoExist(seenResourcePaths, apiDeclaration.resourcePath, 'RESOURCE_PATH', 'Resource path',
['resourcePath'], aResults.errors);
if (adResourcePaths.indexOf(apiDeclaration.resourcePath) === -1) {
// Identify unused resource paths defined in the API Declarations
validateExist(rlResourcePaths, apiDeclaration.resourcePath, 'RESOURCE_PATH', 'Resource path',
['resourcePath'], aResults.errors);
seenResourcePaths.push(apiDeclaration.resourcePath);
}
// TODO: Process authorization references
// Not possible due to https://github.com/swagger-api/swagger-spec/issues/159
// Process models
processDocument(adDocumentMetadata, aResults);
// Process the API definitions
_.reduce(apiDeclaration.apis, function (seenPaths, api, index) {
var aPath = ['apis', index.toString()];
var nPath = normalizePath(api.path);
// Validate duplicate resource path
if (seenPaths.indexOf(nPath.path) > -1) {
createErrorOrWarning('DUPLICATE_API_PATH', 'API path (or equivalent) already defined: ' + api.path,
aPath.concat('path'), aResults.errors);
} else {
seenPaths.push(nPath.path);
}
// Process the API operations
_.reduce(api.operations, function (seenMethods, operation, index) {
var oPath = aPath.concat(['operations', index.toString()]);
// Validate duplicate operation method
validateNoExist(seenMethods, operation.method, 'OPERATION_METHOD', 'Operation method', oPath.concat('method'),
aResults.errors);
// Keep track of the seen methods
seenMethods.push(operation.method);
// Keep track of operation types
if (spec.primitives.indexOf(operation.type) === -1 && spec.version === '1.2') {
addReference(adDocumentMetadata, '#/models/' + operation.type, oPath.concat('type'), aResults);
}
// Process authorization references
processAuthRefs(rlDocumentMetadata, operation.authorizations, oPath.concat('authorizations'), aResults);
// Validate validate inline constraints
validateSchemaConstraints(adDocumentMetadata, operation, oPath, aResults);
// Validate parameters
validateParameters(spec, adDocumentMetadata, nPath, operation.parameters, oPath, aResults);
// Validate unique response code
_.reduce(operation.responseMessages, function (seenResponseCodes, responseMessage, index) {
var rmPath = oPath.concat(['responseMessages', index.toString()]);
validateNoExist(seenResponseCodes, responseMessage.code, 'RESPONSE_MESSAGE_CODE', 'Response message code',
rmPath.concat(['code']), aResults.errors);
// Validate missing model
if (responseMessage.responseModel) {
addReference(adDocumentMetadata, '#/models/' + responseMessage.responseModel,
rmPath.concat('responseModel'), aResults);
}
return seenResponseCodes.concat(responseMessage.code);
}, []);
return seenMethods;
}, []);
return seenPaths;
}, []);
// Validate API Declaration definitions
validateDefinitions(adDocumentMetadata, aResults);
return seenResourcePaths;
}, []);
// Validate API Declaration definitions
validateDefinitions(rlDocumentMetadata, results);
// Identify unused resource paths defined in the Resource Listing
_.each(_.difference(rlResourcePaths, adResourcePaths), function (unused) {
var index = rlResourcePaths.indexOf(unused);
createUnusedErrorOrWarning(resourceListing.apis[index].path, 'RESOURCE_PATH', 'Resource path',
['apis', index.toString(), 'path'], results.errors);
});
callback(undefined, results);
};
var validateSwagger2_0 = function (spec, swaggerObject, callback) { // jshint ignore:line
var documentMetadata = getDocumentCache(swaggerObject);
var results = {
errors: [],
warnings: []
};
// Process definitions
processDocument(documentMetadata, results);
// Process security references
processAuthRefs(documentMetadata, swaggerObject.security, ['security'], results);
_.reduce(documentMetadata.resolved.paths, function (seenPaths, path, name) {
var pPath = ['paths', name];
var nPath = normalizePath(name);
// Validate duplicate resource path
if (seenPaths.indexOf(nPath.path) > -1) {
createErrorOrWarning('DUPLICATE_API_PATH', 'API path (or equivalent) already defined: ' + name, pPath,
results.errors);
}
// Validate parameters
validateParameters(spec, documentMetadata, nPath, path.parameters, pPath, results, true);
// Validate the Operations
_.each(path, function (operation, method) {
var cParams = [];
var oPath = pPath.concat(method);
var seenParams = [];
if (validOptionNames.indexOf(method) === -1) {
return;
}
// Process security references
processAuthRefs(documentMetadata, operation.security, oPath.concat('security'), results);
// Compose parameters from path global parameters and operation parameters
_.each(operation.parameters, function (parameter) {
// Can happen with invalid references
if (_.isUndefined(parameter)) {
return;
}
cParams.push(parameter);
seenParams.push(parameter.name + ':' + parameter.in);
});
_.each(path.parameters, function (parameter) {
var cloned = _.cloneDeep(parameter);
// The only errors that can occur here are schema constraint validation errors which are already reported above
// so do not report them again.
cloned.skipErrors = true;
if (seenParams.indexOf(parameter.name + ':' + parameter.in) === -1) {
cParams.push(cloned);
}
});
// Validate parameters
validateParameters(spec, documentMetadata, nPath, cParams, oPath, results);