This repository has been archived by the owner on Apr 16, 2022. It is now read-only.
/
validator.ts
1691 lines (1429 loc) · 60.1 KB
/
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
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
let workingInput: any = null;
let stopValidation = false;
import resourcesSpec = require('./resourcesSpec');
import logger = require('./logger');
import parser = require('./parser');
const mockArnPrefix = "arn:aws:mock:region:123456789012:";
import {
awsParameterTypes as parameterTypesSpec,
awsRefOverrides,
awsIntrinsicFunctions,
PrimitiveAttribute,
ListAttribute
} from './awsData';
import docs = require('./docs');
import util = require('util');
import CustomError = require('./util/CustomError');
import sms = require('source-map-support');
sms.install();
require('./util/polyfills');
export type ParameterValue = string | string[];
let parameterRuntimeOverride: {[parameter: string]: ParameterValue | undefined} = {};
// Todo: Allow override for RefOverrides ex. Regions
export interface ErrorRecord {
message: string,
resource: string,
documentation: string
}
export interface ErrorObject {
templateValid: boolean,
errors: {
crit: ErrorRecord[],
warn: ErrorRecord[],
info: ErrorRecord[]
},
outputs: {[outputName: string]: string},
exports: {[outputName: string]: string}
}
let errorObject: ErrorObject = {
"templateValid": true,
"errors": {
"info": [],
"warn": [],
"crit": []
},
"outputs": {},
"exports": {}
};
export function resetValidator(){
errorObject = {"templateValid": true, "errors": {"info": [], "warn": [], "crit": []}, outputs: {}, exports: {}};
stopValidation = false;
parameterRuntimeOverride = {};
};
export interface ValidateOptions {
/**
* List of parameters for which guessing is allowed.
* undefined implies all parameters can be guessed.
*/
guessParameters: string[] | undefined;
}
const defaultValidateOptions: ValidateOptions = {
guessParameters: undefined
};
export function validateFile(path: string, options?: Partial<ValidateOptions>){
// Convert to object, this will throw an exception on an error
workingInput = parser.openFile(path);
// Let's go!
return validateWorkingInput(options);
};
export function validateJsonObject(obj: any, options?: Partial<ValidateOptions>){
workingInput = obj;
return validateWorkingInput(options);
};
export function addParameterValue(parameter: string, value: ParameterValue){
addParameterOverride(parameter, value);
};
export function addPseudoValue(parameter: string, value: string){
// Silently drop requests to change AWS::NoValue
if(parameter == 'AWS::NoValue') {
return;
}
// Only process items which are already defined in overrides
if(parameter in awsRefOverrides){
// Put NotificationARNs in an array if required
if(parameter == 'AWS::NotificationARNs'){
if(awsRefOverrides['AWS::NotificationARNs'][0] == 'arn:aws:sns:us-east-1:123456789012:MyTopic'){
awsRefOverrides['AWS::NotificationARNs'][0] = value;
}else{
awsRefOverrides['AWS::NotificationARNs'].push(value);
}
}else{
// By default, replace the value
awsRefOverrides[parameter] = value;
}
}else{
addError('crit', parameter + " is not an allowed pseudo parameter", ['cli-options'], 'pseudo parameters');
}
};
function addParameterOverride(parameter: string, value: ParameterValue){
parameterRuntimeOverride[parameter] = value;
}
function validateWorkingInput(passedOptions?: Partial<ValidateOptions>) {
// Ensure we are working from a clean slate
//exports.resetValidator();
const options = Object.assign({}, defaultValidateOptions, passedOptions);
// Check AWS Template Format Version
if(workingInput.hasOwnProperty(['AWSTemplateFormatVersion'])){
let testValue = workingInput['AWSTemplateFormatVersion'];
if(typeof workingInput['AWSTemplateFormatVersion'] == 'object'){
addError('warn', 'AWSTemplateFormatVersion is recommended to be of type string \'2010-09-09\'', ['AWSTemplateFormatVersion'], 'AWSTemplateFormatVersion')
testValue = testValue.toUTCString();
}
let allowedDateRegex = /^Thu, 09 Sep 2010 00:00:00 GMT$|^2010-09-09$/;
if(!allowedDateRegex.test(testValue)){
addError('crit', 'AWSTemplateFormatVersion should be \'2010-09-09\'', ['AWSTemplateFormatVersion'], 'AWSTemplateFormatVersion');
}
}
// TODO: Check keys for parameter are valid, ex. MinValue/MaxValue
// Check parameters and assign outputs
assignParametersOutput(options.guessParameters);
// Evaluate Conditions
assignConditionsOutputs();
// Assign outputs to all the resources
assignResourcesOutputs();
if(stopValidation) {
// Stop the validation early, we can't join stuff if we don't know what to expect
if(process.env.DEBUG) {
logger.error("Stopping validation early as a resource type is invalid.");
}
return errorObject;
}
// Use the outputs assigned to resources to resolve references
resolveReferences();
// Go through the hopefully resolved properties of each resource
checkResourceProperties();
// Assign template outputs to the error object
collectOutputs();
return errorObject;
}
function assignParametersOutput(guessParameters?: string[]) {
if(!workingInput.hasOwnProperty('Parameters')){
return false; // This isn't an issue
}
const guessAll = (guessParameters === undefined);
const guessParametersSet = new Set(guessParameters || []);
// For through each parameter
for(let parameterName in workingInput['Parameters']) {
const parameter = workingInput['Parameters'][parameterName];
if (!parameter.hasOwnProperty('Type')) {
// We are going to assume type if a string to continue validation, but will throw a critical
addError('crit', `Parameter ${parameterName} does not have a Type defined.`, ['Parameters', parameterName], "Parameters");
parameter['Type'] = 'String';
}
// if the user hasn't specified any parameters to mock, assume all are ok; otherwise,
// only mock the allowed ones.
const okToGuess = (guessAll) || (guessParametersSet.has(parameterName));
let parameterValue = inferParameterValue(parameterName, parameter, okToGuess);
if (parameter.hasOwnProperty('AllowedValues') && parameter['AllowedValues'].indexOf(parameterValue) < 0) {
addError('crit', `Parameter value '${parameterValue}' for ${parameterName} is`
+ ` not within the parameters AllowedValues`, ['Parameters', parameterName], "Parameters");
}
if(parameter['Type'] === "CommaDelimitedList" && typeof parameterValue === 'string') {
parameterValue = parameterValue.split(',').map(x => x.trim());
parameterValue.forEach(val => {
if (val === ""){
addError('crit', `Parameter ${parameterName} contains a CommaDelimitedList where the number of commas appears to be equal or greater than the list of items.`, ['Parameters', parameterName], "Parameters");
}
})
}
// The List<type> parameter value is inferred as string with comma delimited values and must be converted to array
let listParameterTypesSpec = Object.keys(parameterTypesSpec).filter((x) => !!x.match(/List<.*>/));
if (!!~listParameterTypesSpec.indexOf(parameter['Type']) && (typeof parameterValue === 'string')) {
parameterValue = parameterValue.split(',').map(x => x.trim());
parameterValue.forEach(val => {
if (val === ""){
addError('crit', `Parameter ${parameterName} contains a List<${parameter['Type']}> where the number of commas appears to be equal or greater than the list of items.`, ['Parameters', parameterName], "Parameters");
}
})
}
// Assign an Attribute Ref regardless of any failures above
workingInput['Parameters'][parameterName]['Attributes'] = {};
workingInput['Parameters'][parameterName]['Attributes']['Ref'] = parameterValue;
}
}
function inferParameterValue(parameterName: string, parameter: any, okToGuess: boolean): string | string[] {
const parameterDefaultsByType = {
'string': `string_input_${parameterName}`,
'array': undefined,
'number': '42'
}
// Check if the Ref for the parameter has been defined at runtime
const parameterOverride = parameterRuntimeOverride[parameterName]
if (parameterOverride !== undefined) {
// Check the parameter provided at runtime is within the allowed property list (if specified)
return parameterOverride;
} else if (parameter.hasOwnProperty('Default')) {
// See if Default property is present and populate
return parameter['Default'];
} else {
if (!okToGuess) {
addError('crit', 'Value for parameter was not provided', ['Parameters', parameterName], 'Parameters')
}
if (parameter.hasOwnProperty('AllowedValues') && parameter['AllowedValues'].length > 0) {
// See if AllowedValues has been specified
return parameter['AllowedValues'][0];
} else {
const rawParameterType = parameter['Type'];
const listMatch = /^List<(.+)>$/.exec(rawParameterType);
let isList: boolean;
let parameterType: string;
if (listMatch) {
isList = true;
parameterType = listMatch[1];
} else {
parameterType = rawParameterType;
isList = false;
}
if (!parameterTypesSpec.hasOwnProperty(parameterType)) {
addError('crit', `Parameter ${parameterName} has an invalid type of ${rawParameterType}.`, ['Parameters', parameterName], "Parameters");
parameterType = 'String';
}
let normalizedType = parameterTypesSpec[parameterType!];
if (normalizedType == 'array') {
isList = true;
parameterType = 'String';
normalizedType = 'string';
}
const parameterDefault = parameterDefaultsByType[parameterTypesSpec[parameterType]!]!
if (isList) {
return [parameterDefault];
} else {
return parameterDefault;
}
}
}
}
type Severity = keyof typeof errorObject.errors;
function addError(severity: Severity, message : string, resourceStack: typeof placeInTemplate = [], help?: string){
let obj = {
'message': message,
'resource': resourceStack.join(' > '),
'documentation': docs.getUrls(help).join(', ')
};
// Set the information
errorObject.errors[severity].push(obj);
// Template invalid if critical error
if(severity == 'crit'){
errorObject.templateValid = false;
}
// Debug
if(process.env.DEBUG) {
let strResourceStack = resourceStack.join(' > ');
logger.debug(`Error thrown: ${severity}: ${message} (${strResourceStack})`);
}
}
function assignConditionsOutputs(){
let allowedIntrinsicFunctions = ['Fn::And', 'Fn::Equals', 'Fn::If', 'Fn::Not', 'Fn::Or'];
if(!workingInput.hasOwnProperty('Conditions')){
return;
}
// For through each condition
placeInTemplate.push('Conditions');
for(let cond in workingInput['Conditions']) {
if (workingInput['Conditions'].hasOwnProperty(cond)) {
placeInTemplate.push(cond);
let condition = workingInput['Conditions'][cond];
// Check the value of condition is an object
if(typeof condition != 'object'){
addError('crit', `Condition should consist of an intrinsic function of type ${allowedIntrinsicFunctions.join(', ')}`,
placeInTemplate,
'Conditions');
workingInput['Conditions'][cond] = {};
workingInput['Conditions'][cond]['Attributes'] = {};
workingInput['Conditions'][cond]['Attributes']['Output'] = false;
}else{
// Check the value of this is Fn::And, Fn::Equals, Fn::If, Fn::Not or Fn::Or
let keys = Object.keys(condition);
if(allowedIntrinsicFunctions.indexOf(keys[0]) != -1){
// Resolve recursively
let val = resolveIntrinsicFunction(condition, keys[0]);
// Check is boolean type
workingInput['Conditions'][cond]['Attributes'] = {};
workingInput['Conditions'][cond]['Attributes']['Output'] = false;
if(val === true || val === false){
workingInput['Conditions'][cond]['Attributes']['Output'] = val;
}else{
addError('crit', `Condition did not resolve to a boolean value, got ${val}`, placeInTemplate, 'Conditions');
}
}else{
// Invalid intrinsic function
addError('crit', `Condition does not allow function '${keys[0]}' here`, placeInTemplate, 'Conditions');
}
}
placeInTemplate.pop();
}
}
placeInTemplate.pop();
}
function assignResourcesOutputs(){
if(!workingInput.hasOwnProperty('Resources')){
addError('crit', 'Resources section is not defined', [], "Resources");
stopValidation = true;
return false;
}
if(workingInput['Resources'].length == 0){
addError('crit', 'Resources is empty', [], "Resources");
stopValidation = true;
return false;
}
// For through each resource
for(let res in workingInput['Resources']){
if(workingInput['Resources'].hasOwnProperty(res)){
// Check if Type is defined
let resourceType = null;
let spec = null;
if(!workingInput['Resources'][res].hasOwnProperty('Type')){
stopValidation = true;
addError('crit',
`Resource ${res} does not have a Type.`,
['Resources', res],
"Resources"
);
}else{
// Check if Type is valid
resourceType = workingInput['Resources'][res]['Type'];
try {
spec = resourcesSpec.getResourceType(workingInput['Resources'][res]['Type']);
} catch (e) {
if (e instanceof resourcesSpec.NoSuchResourceType) {
addError('crit',
`Resource ${res} has an invalid Type of ${resourceType}.`,
['Resources', res],
"Resources"
);
} else {
throw e;
}
}
}
// Create a map for storing the output attributes for this Resource
let refValue = "mock-ref-" + res;
let refOverride = resourcesSpec.getRefOverride(resourceType);
if(refOverride !== null){
if(refOverride == "arn"){
refValue = mockArnPrefix + res;
}else{
refValue = refOverride;
}
}
// Create a return attributes for the resource, assume every resource has a Ref
workingInput['Resources'][res]['Attributes'] = {};
workingInput['Resources'][res]['Attributes']['Ref'] = refValue;
// Go through the attributes of the specification, and assign them
if(spec != null && spec.Attributes){
for(let attr in spec.Attributes){
if (attr.indexOf('Arn') != -1) {
workingInput['Resources'][res]['Attributes'][attr] = mockArnPrefix + res;
}else {
workingInput['Resources'][res]['Attributes'][attr] = "mockAttr_" + res;
}
}
}
}
}
}
function resolveReferences(){
// TODO: Go through and resolve...
// TODO: Ref, Attr, Join,
// Resolve all Ref
lastPositionInTemplate = workingInput;
recursiveDecent(lastPositionInTemplate);
let stop = workingInput;
}
let placeInTemplate: (string|number)[] = [];
let lastPositionInTemplate: any = null;
let lastPositionInTemplateKey: string | null = null;
function recursiveDecent(ref: any){
// Step into next attribute
for(let i=0; i < Object.keys(ref).length; i++){
let key = Object.keys(ref)[i];
// Resolve the function
if(awsIntrinsicFunctions.hasOwnProperty(key)){
// Check if an Intrinsic function is allowed here
let inResourceProperty = (placeInTemplate[0] == "Resources" || placeInTemplate[2] == "Properties");
let inResourceMetadata = (placeInTemplate[0] == "Resources" || placeInTemplate[2] == "Metadata");
let inOutputs = (placeInTemplate[0] == "Outputs");
let inConditions = (placeInTemplate[0] == "Conditions");
// TODO Check for usage inside update policy
if(!(inResourceProperty || inResourceMetadata || inOutputs || inConditions)){
addError("crit", `Intrinsic function ${key} is not supported here`, placeInTemplate, key);
}else {
// Resolve the function
let functionOutput = resolveIntrinsicFunction(ref, key);
if (functionOutput !== null && lastPositionInTemplateKey !== null) {
// Overwrite the position with the resolved value
lastPositionInTemplate[lastPositionInTemplateKey] = functionOutput;
}
}
}else if(key != 'Attributes' && ref[key] instanceof Object){
placeInTemplate.push(key);
lastPositionInTemplate = ref;
lastPositionInTemplateKey = key;
recursiveDecent(ref[key]);
}
}
placeInTemplate.pop();
}
function resolveCondition(ref: any, key: string){
let toGet = ref[key];
let condition = false;
if(workingInput.hasOwnProperty('Conditions') && workingInput['Conditions'].hasOwnProperty(toGet)){
// Check the valid of the condition, returning argument 1 on true or 2 on failure
if(typeof workingInput['Conditions'][toGet] == 'object') {
if (workingInput['Conditions'][toGet].hasOwnProperty('Attributes') &&
workingInput['Conditions'][toGet]['Attributes'].hasOwnProperty('Output')) {
condition = workingInput['Conditions'][toGet]['Attributes']['Output'];
} // If invalid, we will default to false, a previous error would have been thrown
}else{
condition = workingInput['Conditions'][toGet];
}
}else{
addError('crit', `Condition '${toGet}' must reference a valid condition`, placeInTemplate, 'Condition');
}
return condition;
}
function resolveIntrinsicFunction(ref: any, key: string) : string | boolean | string[] | undefined | null{
switch(key){
case 'Ref':
return doIntrinsicRef(ref, key);
case 'Condition':
return resolveCondition(ref, key);
case 'Fn::Join':
return doIntrinsicJoin(ref, key);
case 'Fn::Base64':
return doIntrinsicBase64(ref, key);
case 'Fn::GetAtt':
return doIntrinsicGetAtt(ref, key);
case 'Fn::FindInMap':
return doIntrinsicFindInMap(ref, key);
case 'Fn::GetAZs':
return doIntrinsicGetAZs(ref, key);
case 'Fn::Sub':
return doIntrinsicSub(ref, key);
case 'Fn::If':
return doIntrinsicIf(ref, key);
case 'Fn::Equals':
return doIntrinsicEquals(ref, key);
case 'Fn::Or':
return doIntrinsicOr(ref, key);
case 'Fn::Not':
return doIntrinsicNot(ref, key);
case 'Fn::ImportValue':
return doIntrinsicImportValue(ref, key);
case 'Fn::Select':
return doIntrinsicSelect(ref, key);
case 'Fn::Split':
return doInstrinsicSplit(ref, key);
default:
addError("warn", `Unhandled Intrinsic Function ${key}, this needs implementing. Some errors might be missed.`, placeInTemplate, "Functions");
return null;
}
}
function doIntrinsicRef(ref: any, key: string){
let refValue = ref[key];
let resolvedVal = "INVALID_REF";
// Check if it's of a String type
if(typeof refValue != "string"){
addError("crit", "Intrinsic Function Ref expects a string", placeInTemplate, "Ref");
}else {
// Check if the value of the Ref exists
resolvedVal = getRef(refValue);
if (resolvedVal === null) {
addError('crit', `Referenced value ${refValue} does not exist`, placeInTemplate, "Ref");
resolvedVal = "INVALID_REF";
}
}
// Return the resolved value
return resolvedVal;
}
function doIntrinsicBase64(ref: any, key: string){
// Only base64 encode strings
let toEncode = ref[key];
if(typeof toEncode != "string"){
toEncode = resolveIntrinsicFunction(ref[key], Object.keys(ref[key])[0]);
if(typeof toEncode != "string"){
addError("crit", "Parameter of Fn::Base64 does not resolve to a string", placeInTemplate, "Fn::Base64");
return "INVALID_FN_BASE64";
}
}
// Return base64
return Buffer.from(toEncode).toString('base64');
}
function doIntrinsicJoin(ref: any, key: string){
// Ensure that all objects in the join array have been resolved to string, otherwise
// we need to resolve them.
// Expect 2 parameters
let join = ref[key][0];
let parts = ref[key][1] || null;
if(ref[key].length != 2 || parts == null){
addError('crit', 'Invalid parameters for Fn::Join', placeInTemplate, "Fn::Join");
// Specify this as an invalid string
return "INVALID_JOIN";
}else{
// Join
return fnJoin(join, parts);
}
}
function doIntrinsicGetAtt(ref: any, key: string){
let toGet = ref[key];
if(toGet.length < 2){
addError("crit", "Invalid parameters for Fn::GetAtt", placeInTemplate, "Fn::GetAtt");
return "INVALID_GET_ATT"
}else{
if(typeof toGet[0] != "string"){ // TODO Implement unit test for this
addError("crit", "Fn::GetAtt does not support functions for the logical resource name", placeInTemplate, "Fn::GetAtt");
}
// If we have more than 2 parameters, merge other parameters
if(toGet.length > 2){
let root = toGet[0];
let parts = toGet.slice(1).join('.');
toGet = [root, parts];
}
// The AttributeName could be a Ref, so check if it needs resolving
if(typeof toGet[1] != "string"){
let keys = Object.keys(toGet[1]);
if(keys[0] == "Ref") { // TODO Implement unit test for this
toGet[1] = resolveIntrinsicFunction(toGet[1], "Ref");
}else{ // TODO Implement unit test for this
addError("crit", "Fn::GetAtt only supports Ref within the AttributeName", placeInTemplate, "Fn::GetAtt");
}
}
let attr = fnGetAtt(toGet[0], toGet[1]);
if(attr != null){
return attr;
}else{
return "INVALID_REFERENCE_OR_ATTR_ON_GET_ATT";
}
}
}
function doIntrinsicFindInMap(ref: any, key: string){
let toGet = ref[key];
if(toGet.length != 3){
addError("crit", "Invalid parameters for Fn::FindInMap", placeInTemplate, "Fn::FindInMap");
return "INVALID_FN_FIND_IN_MAP"
}else {
for(let x in toGet){
if(toGet.hasOwnProperty(x)) {
if (typeof toGet[x] != "string") {
toGet[x] = resolveIntrinsicFunction(toGet[x], Object.keys(toGet[x])[0]);
}
}
}
// Find in map
let val = fnFindInMap(toGet[0], toGet[1], toGet[2]);
if(val == null){
addError("crit",
`Could not find value in map ${toGet[0]}|${toGet[1]}|${toGet[2]}. Have you tried specifying input parameters?`,
placeInTemplate,
"Fn::FindInMap");
return "INVALID_MAPPING";
}else{
return val;
}
}
}
function doIntrinsicGetAZs(ref: any, key: string){
let toGet = ref[key];
let region = awsRefOverrides['AWS::Region'];
// If the argument is not a string, check it's Ref and resolve
if(typeof toGet != "string"){
let key = Object.keys(toGet)[0];
if(key == "Ref") {
if(toGet[key] != 'AWS::Region'){
addError("warn", "Fn::GetAZs expects a region, ensure this reference returns a region", placeInTemplate, "Fn::GetAZs");
}
region = resolveIntrinsicFunction(toGet, "Ref") as string;
}else{ // TODO Implement unit test for this
addError("crit", "Fn::GetAZs only supports Ref or string as a parameter", placeInTemplate, "Fn::GetAZs");
}
}else{
if(toGet != ""){ // TODO: Implement unit test
region = toGet;
}
}
// We now have a string, assume it's a real region
// Lets create an array with 3 AZs
let AZs = [];
AZs.push(region + 'a');
AZs.push(region + 'b');
AZs.push(region + 'c');
return AZs;
}
function doIntrinsicSelect(ref: any, key: string){
let toGet = ref[key];
if(!Array.isArray(toGet) || toGet.length < 2) {
addError('crit', "Fn::Select only supports an array of two elements", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
if (toGet[0] === undefined || toGet[0] === null) {
addError('crit', "Fn::Select first element cannot be null or undefined", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
let index: number;
if (typeof toGet[0] == 'object' && !Array.isArray(toGet[0])) {
let keys = Object.keys(toGet[0]);
if(awsIntrinsicFunctions['Fn::Select::Index']['supportedFunctions'].indexOf(keys[0]) != -1) {
let resolvedIndex = resolveIntrinsicFunction(toGet[0], keys[0]);
if(typeof resolvedIndex === 'string') {
index = parseInt(resolvedIndex);
} else if (typeof resolvedIndex === 'number') {
index = resolvedIndex;
} else {
addError('crit', "Fn::Select's first argument did not resolve to a string for parsing or a numeric value.", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
} else {
addError('crit', `Fn::Select does not support the ${keys[0]} function in argument 1`);
return 'INVALID_SELECT';
}
} else if (typeof toGet[0] === 'string') {
index = parseInt(toGet[0])
} else if (typeof toGet[0] === 'number'){
index = toGet[0];
} else {
addError('crit', `Fn:Select's first argument must be a number or resolve to a number, it appears to be a ${typeof(toGet[0])}`, placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
if (typeof index === undefined || typeof index !== 'number' || isNaN(index)) {
addError('crit', "First element of Fn::Select must be a number, or it must use an intrinsic fuction that returns a number", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
if (toGet[1] === undefined || toGet[1] === null) {
addError('crit', "Fn::Select Second element cannot be null or undefined", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
let list = toGet[1]
if (!Array.isArray(list)) {
//we may need to resolve it
if (typeof list !== 'object') {
addError('crit', `Fn::Select requires the second element to resolve to a list, it appears to be a ${typeof list}`, placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
} else if(typeof list == 'object'){
let keys = Object.keys(list);
if(awsIntrinsicFunctions['Fn::Select::List']['supportedFunctions'].indexOf(keys[0]) != -1) {
list = resolveIntrinsicFunction(list, keys[0]);
} else {
addError('crit', `Fn::Select does not support the ${keys[0]} function in argument 2`);
return 'INVALID_SELECT';
}
if (keys[0] === "Ref" ) {
// check if it was a paramter which might be converted to a list
const parameterName = toGet[1][keys[0]];
if (workingInput['Parameters'][parameterName] !== undefined ) {
list = workingInput['Parameters'][parameterName]['Attributes']['Ref'];
}
}
}
if (!Array.isArray(list)) {
addError('crit', `Fn::Select requires the second element to be a list, function call did not resolve to a list. It contains value ${list}`, placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
} else if (list.indexOf(null) > -1) {
addError('crit', "Fn::Select requires that the list be free of null values", placeInTemplate, "Fn::Select");
}
if (index >= 0 && index < list.length) {
return list[index];
} else {
addError('crit', "First element of Fn::Select exceeds the length of the list.", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
}
function doIntrinsicSub(ref: any, key: string){
let toGet = ref[key];
let replacementStr = null;
let definedParams = null;
// We have a simple replace
if(typeof toGet == 'string'){
replacementStr = toGet;
}else{
// We should have an array of parameters
if(toGet[0]){
if(typeof toGet[0] == 'string'){
replacementStr = toGet[0];
}else{
addError('crit', 'Fn::Sub expects first argument to be a string', placeInTemplate, 'Fn::Sub');
}
if(typeof toGet[1] == 'object'){
definedParams = toGet[1];
}else{
addError('crit', 'Fn::Sub expects second argument to be a variable map', placeInTemplate, 'Fn::Sub');
}
}else{
addError('crit', 'Fn::Sub function malformed, first array element should be present', placeInTemplate, "Fn::Sub");
}
}
// Extract the replacement parts
let regex = /\${([A-Za-z0-9:.!]+)/gm;
let matches = [];
let match;
while (match = regex.exec(replacementStr)) {
matches.push(match[1]);
}
// Resolve the replacement and replace into string using Ref or GetAtt
for(let m of matches){
let replacementVal = "";
if(m.indexOf('!') == 1){
// Literal Value
replacementVal = m;
}else if(m.indexOf('.') != -1){
// Check if m is within the key value map
if(definedParams !== null && definedParams.hasOwnProperty(m) && typeof definedParams[m] !== 'string'){
definedParams[m] = resolveIntrinsicFunction(definedParams[m], Object.keys(m)[0]);
replacementVal = definedParams[m];
}else{
// Use Fn::GetAtt
let parts = m.split('.');
replacementVal = fnGetAtt(parts[0], parts[1]);
if(replacementVal === null){
addError('crit', `Intrinsic Sub does not reference valid resource attribute '${m}'`, placeInTemplate, 'Fn::Sub');
}
}
}else{
if(definedParams !== null && definedParams.hasOwnProperty(m)){
if(typeof definedParams[m] !== 'string') {
replacementVal = resolveIntrinsicFunction(definedParams[m], Object.keys(m)[0]) as string;
}else{
replacementVal = definedParams[m];
}
}else {
// Use Ref
replacementVal = getRef(m);
if(replacementVal === null){
addError('crit', `Intrinsic Sub does not reference valid resource or mapping '${m}'`, placeInTemplate, 'Fn::Sub');
}
}
}
// Do a string replace on the string
replacementStr = replacementStr.replace("${" + m + "}", replacementVal);
}
// Set the resolved value as a string
return replacementStr;
}
function doIntrinsicIf(ref: any, key: string){
let toGet = ref[key];
// Check the value of the condition
if(toGet.length == 3){
// Check toGet[0] is a valid condition
toGet[0] = resolveCondition({'Condition': toGet[0]}, 'Condition');
// Set the value
let value = null;
if(toGet[0]){
value = toGet[1];
}else{
value = toGet[2];
}
if(value instanceof Array){
// Go through each element in the array, resolving if needed.
let resolvedValue = [];
for(let i=0; i < value.length; i++) {
let keys = Object.keys(value[i]);
if (awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) !== -1) {
resolvedValue.push(resolveIntrinsicFunction(value[i], keys[0]));
}else{
addError('crit', `Fn::If does not allow ${keys[0]} as a nested function within an array`, placeInTemplate, 'Fn::If');
}
}
// Return the resolved array
return resolvedValue;
}else if(typeof value === "object") {
let keys = Object.keys(value);
if (awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) !== -1) {
return resolveIntrinsicFunction(value, keys[0]);
}else{
addError('crit', `Fn::If does not allow ${keys[0]} as a nested function`, placeInTemplate, 'Fn::If');
}
}else {
return value;
}
}else{
addError('crit', `Fn::If must have 3 arguments, only ${toGet.length} given.`, placeInTemplate, 'Fn::If');
}
// Set the 1st or 2nd param as according to the condition
return "INVALID_IF_STATEMENT";
}
function doIntrinsicEquals(ref: any, key: string) {
let toGet = ref[key];
// Check the value of the condition
if (toGet.length == 2) {
// Resolve first argument
if(typeof toGet[0] == 'object'){
let keys = Object.keys(toGet[0]);
if(awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[0] = resolveIntrinsicFunction(toGet[0], keys[0]);
}else{
addError('crit', `Fn::Equals does not support the ${keys[0]} function in argument 1`);
}
}
// Resolve second argument
if(typeof toGet[1] == 'object'){
let keys = Object.keys(toGet[1]);
if(awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[0] = resolveIntrinsicFunction(toGet[1], keys[0]);
}else{
addError('crit', `Fn::Equals does not support the ${keys[1]} function in argument 2`);
}
}
// Compare
return (toGet[0] == toGet[1]);
}else{
addError('crit', `Fn::Equals expects 2 arguments, ${toGet.length} given.`, placeInTemplate, 'Fn::Equals');
}
return false;
}
function doIntrinsicOr(ref: any, key: string) {
let toGet = ref[key];
// Check the value of the condition
if (toGet.length > 1 && toGet.length < 11) {
let argumentIsTrue = false;
// Resolve each argument
for(let arg in toGet){
if(toGet.hasOwnProperty(arg)) {
if (typeof toGet[arg] == 'object') {
let keys = Object.keys(toGet[arg]);
if(awsIntrinsicFunctions['Fn::Or']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[arg] = resolveIntrinsicFunction(toGet[arg], keys[0]);
}else{
addError('crit', `Fn::Or does not support function '${keys[0]}' here`, placeInTemplate, 'Fn::Or');
}
}
// Set to true if needed
if (toGet[arg] === true) {
argumentIsTrue = true;
}
}
}
return argumentIsTrue;
}else{
addError('crit', `Expecting Fn::Or to have between 2 and 10 arguments`, placeInTemplate, 'Fn::Or');
}
}
function doIntrinsicNot(ref: any, key: string){