-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathswagger.py
905 lines (730 loc) · 39.5 KB
/
swagger.py
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
import copy
import json
import re
from six import string_types
from samtranslator.model.intrinsics import ref
from samtranslator.model.intrinsics import make_conditional
from samtranslator.model.exceptions import InvalidDocumentException, InvalidTemplateException
class SwaggerEditor(object):
"""
Wrapper class capable of parsing and generating Swagger JSON. This implements Swagger spec just enough that SAM
cares about. It is built to handle "partial Swagger" ie. Swagger that is incomplete and won't
pass the Swagger spec. But this is necessary for SAM because it iteratively builds the Swagger starting from an
empty skeleton.
"""
_OPTIONS_METHOD = "options"
_X_APIGW_INTEGRATION = 'x-amazon-apigateway-integration'
_X_APIGW_BINARY_MEDIA_TYPES = 'x-amazon-apigateway-binary-media-types'
_CONDITIONAL_IF = "Fn::If"
_X_APIGW_GATEWAY_RESPONSES = 'x-amazon-apigateway-gateway-responses'
_X_APIGW_POLICY = 'x-amazon-apigateway-policy'
_X_ANY_METHOD = 'x-amazon-apigateway-any-method'
def __init__(self, doc):
"""
Initialize the class with a swagger dictionary. This class creates a copy of the Swagger and performs all
modifications on this copy.
:param dict doc: Swagger document as a dictionary
:raises ValueError: If the input Swagger document does not meet the basic Swagger requirements.
"""
if not SwaggerEditor.is_valid(doc):
raise ValueError("Invalid Swagger document")
self._doc = copy.deepcopy(doc)
self.paths = self._doc["paths"]
self.security_definitions = self._doc.get("securityDefinitions", {})
self.gateway_responses = self._doc.get(self._X_APIGW_GATEWAY_RESPONSES, {})
self.resource_policy = self._doc.get(self._X_APIGW_POLICY, {})
self.definitions = self._doc.get('definitions', {})
def get_path(self, path):
path_dict = self.paths.get(path)
if isinstance(path_dict, dict) and self._CONDITIONAL_IF in path_dict:
path_dict = path_dict[self._CONDITIONAL_IF][1]
return path_dict
def has_path(self, path, method=None):
"""
Returns True if this Swagger has the given path and optional method
:param string path: Path name
:param string method: HTTP method
:return: True, if this path/method is present in the document
"""
method = self._normalize_method_name(method)
path_dict = self.get_path(path)
path_dict_exists = path_dict is not None
if method:
return path_dict_exists and method in path_dict
return path_dict_exists
def method_has_integration(self, method):
"""
Returns true if the given method contains a valid method definition.
This uses the get_method_contents function to handle conditionals.
:param dict method: method dictionary
:return: true if method has one or multiple integrations
"""
for method_definition in self.get_method_contents(method):
if self.method_definition_has_integration(method_definition):
return True
return False
def method_definition_has_integration(self, method_definition):
"""
Checks a method definition to make sure it has an apigw integration
:param dict method_defintion: method definition dictionary
:return: True if an integration exists
"""
if method_definition.get(self._X_APIGW_INTEGRATION):
return True
return False
def get_method_contents(self, method):
"""
Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: method dictionary
:return: list of swagger component dictionaries for the method
"""
if self._CONDITIONAL_IF in method:
return method[self._CONDITIONAL_IF][1:]
return [method]
def has_integration(self, path, method):
"""
Checks if an API Gateway integration is already present at the given path/method
:param string path: Path name
:param string method: HTTP method
:return: True, if an API Gateway integration is already present
"""
method = self._normalize_method_name(method)
path_dict = self.get_path(path)
return self.has_path(path, method) and \
isinstance(path_dict[method], dict) and \
self.method_has_integration(path_dict[method]) # Integration present and non-empty
def add_path(self, path, method=None):
"""
Adds the path/method combination to the Swagger, if not already present
:param string path: Path name
:param string method: HTTP method
:raises ValueError: If the value of `path` in Swagger is not a dictionary
"""
method = self._normalize_method_name(method)
path_dict = self.paths.setdefault(path, {})
if not isinstance(path_dict, dict):
# Either customers has provided us an invalid Swagger, or this class has messed it somehow
raise InvalidDocumentException(
[InvalidTemplateException("Value of '{}' path must be a dictionary according to Swagger spec."
.format(path))])
if self._CONDITIONAL_IF in path_dict:
path_dict = path_dict[self._CONDITIONAL_IF][1]
path_dict.setdefault(method, {})
def add_lambda_integration(self, path, method, integration_uri,
method_auth_config=None, api_auth_config=None, condition=None):
"""
Adds aws_proxy APIGW integration to the given path+method.
:param string path: Path name
:param string method: HTTP Method
:param string integration_uri: URI for the integration.
"""
method = self._normalize_method_name(method)
if self.has_integration(path, method):
raise ValueError("Lambda integration already exists on Path={}, Method={}".format(path, method))
self.add_path(path, method)
# Wrap the integration_uri in a Condition if one exists on that function
# This is necessary so CFN doesn't try to resolve the integration reference.
if condition:
integration_uri = make_conditional(condition, integration_uri)
path_dict = self.get_path(path)
path_dict[method][self._X_APIGW_INTEGRATION] = {
'type': 'aws_proxy',
'httpMethod': 'POST',
'uri': integration_uri
}
method_auth_config = method_auth_config or {}
api_auth_config = api_auth_config or {}
if method_auth_config.get('Authorizer') == 'AWS_IAM' \
or api_auth_config.get('DefaultAuthorizer') == 'AWS_IAM' and not method_auth_config:
method_invoke_role = method_auth_config.get('InvokeRole')
if not method_invoke_role and 'InvokeRole' in method_auth_config:
method_invoke_role = 'NONE'
api_invoke_role = api_auth_config.get('InvokeRole')
if not api_invoke_role and 'InvokeRole' in api_auth_config:
api_invoke_role = 'NONE'
credentials = self._generate_integration_credentials(
method_invoke_role=method_invoke_role,
api_invoke_role=api_invoke_role
)
if credentials and credentials != 'NONE':
self.paths[path][method][self._X_APIGW_INTEGRATION]['credentials'] = credentials
# If 'responses' key is *not* present, add it with an empty dict as value
path_dict[method].setdefault('responses', {})
# If a condition is present, wrap all method contents up into the condition
if condition:
path_dict[method] = make_conditional(condition, path_dict[method])
def make_path_conditional(self, path, condition):
"""
Wrap entire API path definition in a CloudFormation if condition.
"""
self.paths[path] = make_conditional(condition, self.paths[path])
def _generate_integration_credentials(self, method_invoke_role=None, api_invoke_role=None):
return self._get_invoke_role(method_invoke_role or api_invoke_role)
def _get_invoke_role(self, invoke_role):
CALLER_CREDENTIALS_ARN = 'arn:aws:iam::*:user/*'
return invoke_role if invoke_role and invoke_role != 'CALLER_CREDENTIALS' else CALLER_CREDENTIALS_ARN
def iter_on_path(self):
"""
Yields all the paths available in the Swagger. As a caller, if you add new paths to Swagger while iterating,
they will not show up in this iterator
:yields string: Path name
"""
for path, value in self.paths.items():
yield path
def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None,
allow_credentials=None):
"""
Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that
will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers
into the actual response returned from Lambda function. This is something customers have to implement
themselves.
If OPTIONS method is already present for the Path, we will skip adding CORS configuration
Following this guide:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool
:param string path: Path to add the CORS configuration to.
:param string/dict allowed_origins: Comma separate list of allowed origins.
Value can also be an intrinsic function dict.
:param string/dict allowed_headers: Comma separated list of allowed headers.
Value can also be an intrinsic function dict.
:param string/dict allowed_methods: Comma separated list of allowed methods.
Value can also be an intrinsic function dict.
:param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on
Access-Control-Max-Age header. Value can also be an intrinsic function dict.
:param bool/None allow_credentials: Flags whether request is allowed to contain credentials.
:raises ValueError: When values for one of the allowed_* variables is empty
"""
# Skip if Options is already present
if self.has_path(path, self._OPTIONS_METHOD):
return
if not allowed_origins:
raise ValueError("Invalid input. Value for AllowedOrigins is required")
if not allowed_methods:
# AllowMethods is not given. Let's try to generate the list from the given Swagger.
allowed_methods = self._make_cors_allowed_methods_for_path(path)
# APIGW expects the value to be a "string expression". Hence wrap in another quote. Ex: "'GET,POST,DELETE'"
allowed_methods = "'{}'".format(allowed_methods)
if allow_credentials is not True:
allow_credentials = False
# Add the Options method and the CORS response
self.add_path(path, self._OPTIONS_METHOD)
self.get_path(path)[self._OPTIONS_METHOD] = self._options_method_response_for_cors(allowed_origins,
allowed_headers,
allowed_methods,
max_age,
allow_credentials)
def add_binary_media_types(self, binary_media_types):
bmt = json.loads(json.dumps(binary_media_types).replace('~1', '/'))
self._doc[self._X_APIGW_BINARY_MEDIA_TYPES] = bmt
def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None,
max_age=None, allow_credentials=None):
"""
Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS.
This snippet is taken from public documentation:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool
:param string/dict allowed_origins: Comma separate list of allowed origins.
Value can also be an intrinsic function dict.
:param string/dict allowed_headers: Comma separated list of allowed headers.
Value can also be an intrinsic function dict.
:param string/dict allowed_methods: Comma separated list of allowed methods.
Value can also be an intrinsic function dict.
:param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on
Access-Control-Max-Age header. Value can also be an intrinsic function dict.
:param bool allow_credentials: Flags whether request is allowed to contain credentials.
:return dict: Dictionary containing Options method configuration for CORS
"""
ALLOW_ORIGIN = "Access-Control-Allow-Origin"
ALLOW_HEADERS = "Access-Control-Allow-Headers"
ALLOW_METHODS = "Access-Control-Allow-Methods"
MAX_AGE = "Access-Control-Max-Age"
ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"
HEADER_RESPONSE = (lambda x: "method.response.header." + x)
response_parameters = {
# AllowedOrigin is always required
HEADER_RESPONSE(ALLOW_ORIGIN): allowed_origins
}
response_headers = {
# Allow Origin is always required
ALLOW_ORIGIN: {
"type": "string"
}
}
# Optional values. Skip the header if value is empty
#
# The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and
# not supported in all the browsers. So it is important to skip the header if value is not given
# https://fetch.spec.whatwg.org/#http-new-header-syntax
#
if allowed_headers:
response_parameters[HEADER_RESPONSE(ALLOW_HEADERS)] = allowed_headers
response_headers[ALLOW_HEADERS] = {"type": "string"}
if allowed_methods:
response_parameters[HEADER_RESPONSE(ALLOW_METHODS)] = allowed_methods
response_headers[ALLOW_METHODS] = {"type": "string"}
if max_age is not None:
# MaxAge can be set to 0, which is a valid value. So explicitly check against None
response_parameters[HEADER_RESPONSE(MAX_AGE)] = max_age
response_headers[MAX_AGE] = {"type": "integer"}
if allow_credentials is True:
# Allow-Credentials only has a valid value of true, it should be omitted otherwise.
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
response_parameters[HEADER_RESPONSE(ALLOW_CREDENTIALS)] = "'true'"
response_headers[ALLOW_CREDENTIALS] = {"type": "string"}
return {
"summary": "CORS support",
"consumes": ["application/json"],
"produces": ["application/json"],
self._X_APIGW_INTEGRATION: {
"type": "mock",
"requestTemplates": {
"application/json": "{\n \"statusCode\" : 200\n}\n"
},
"responses": {
"default": {
"statusCode": "200",
"responseParameters": response_parameters,
"responseTemplates": {
"application/json": "{}\n"
}
}
}
},
"responses": {
"200": {
"description": "Default response for CORS method",
"headers": response_headers
}
}
}
def _make_cors_allowed_methods_for_path(self, path):
"""
Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this
path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will
be returned as result.
:param string path: Path to generate AllowMethods value for
:return string: String containing the value of AllowMethods, if the path contains any methods.
Empty string, otherwise
"""
# https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
all_http_methods = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"]
if not self.has_path(path):
return ""
# At this point, value of Swagger path should be a dictionary with method names being the keys
methods = list(self.get_path(path).keys())
if self._X_ANY_METHOD in methods:
# API Gateway's ANY method is not a real HTTP method but a wildcard representing all HTTP methods
allow_methods = all_http_methods
else:
allow_methods = methods
allow_methods.append("options") # Always add Options to the CORS methods response
# Clean up the result:
#
# - HTTP Methods **must** be upper case and they are case sensitive.
# (https://tools.ietf.org/html/rfc7231#section-4.1)
# - Convert to set to remove any duplicates
# - Sort to keep this list stable because it could be constructed from dictionary keys which are *not* ordered.
# Therefore we might get back a different list each time the code runs. To prevent any unnecessary
# regression, we sort the list so the returned value is stable.
allow_methods = list({m.upper() for m in allow_methods})
allow_methods.sort()
# Allow-Methods is comma separated string
return ','.join(allow_methods)
def add_authorizers_security_definitions(self, authorizers):
"""
Add Authorizer definitions to the securityDefinitions part of Swagger.
:param list authorizers: List of Authorizer configurations which get translated to securityDefinitions.
"""
self.security_definitions = self.security_definitions or {}
for authorizer_name, authorizer in authorizers.items():
self.security_definitions[authorizer_name] = authorizer.generate_swagger()
def add_awsiam_security_definition(self):
"""
Adds AWS_IAM definition to the securityDefinitions part of Swagger.
Note: this method is idempotent
"""
aws_iam_security_definition = {
'AWS_IAM': {
'x-amazon-apigateway-authtype': 'awsSigv4',
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
}
self.security_definitions = self.security_definitions or {}
# Only add the security definition if it doesn't exist. This helps ensure
# that we minimize changes to the swagger in the case of user defined swagger
if 'AWS_IAM' not in self.security_definitions:
self.security_definitions.update(aws_iam_security_definition)
def add_apikey_security_definition(self):
"""
Adds api_key definition to the securityDefinitions part of Swagger.
Note: this method is idempotent
"""
api_key_security_definition = {
'api_key': {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
}
}
self.security_definitions = self.security_definitions or {}
# Only add the security definition if it doesn't exist. This helps ensure
# that we minimize changes to the swagger in the case of user defined swagger
if 'api_key' not in self.security_definitions:
self.security_definitions.update(api_key_security_definition)
def set_path_default_authorizer(self, path, default_authorizer, authorizers,
add_default_auth_to_preflight=True):
"""
Adds the default_authorizer to the security block for each method on this path unless an Authorizer
was defined at the Function/Path/Method level. This is intended to be used to set the
authorizer security restriction for all api methods based upon the default configured in the
Serverless API.
:param string path: Path name
:param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the
authorizers param.
:param list authorizers: List of Authorizer configurations defined on the related Api.
:param bool add_default_auth_to_preflight: Bool of whether to add the default
authorizer to OPTIONS preflight requests.
"""
for method_name, method in self.get_path(path).items():
normalized_method_name = self._normalize_method_name(method_name)
# Excluding paramters section
if normalized_method_name == "parameters":
continue
if add_default_auth_to_preflight or normalized_method_name != "options":
normalized_method_name = self._normalize_method_name(method_name)
# It is possible that the method could have two definitions in a Fn::If block.
for method_definition in self.get_method_contents(self.get_path(path)[normalized_method_name]):
# If no integration given, then we don't need to process this definition (could be AWS::NoValue)
if not self.method_definition_has_integration(method_definition):
continue
existing_security = method_definition.get('security', [])
authorizer_list = ['AWS_IAM']
if authorizers:
authorizer_list.extend(authorizers.keys())
authorizer_names = set(authorizer_list)
existing_non_authorizer_security = []
existing_authorizer_security = []
# Split existing security into Authorizers and everything else
# (e.g. sigv4 (AWS_IAM), api_key (API Key/Usage Plans), NONE (marker for ignoring default))
# We want to ensure only a single Authorizer security entry exists while keeping everything else
for security in existing_security:
if authorizer_names.isdisjoint(security.keys()):
existing_non_authorizer_security.append(security)
else:
existing_authorizer_security.append(security)
none_idx = -1
authorizer_security = []
# Check for an existing Authorizer before applying the default. It would be simpler
# if instead we applied the DefaultAuthorizer first and then simply
# overwrote it if necessary, however, the order in which things get
# applied (Function Api Events first; then Api Resource) complicates it.
# Check if Function/Path/Method specified 'NONE' for Authorizer
for idx, security in enumerate(existing_non_authorizer_security):
is_none = any(key == 'NONE' for key in security.keys())
if is_none:
none_idx = idx
break
# NONE was found; remove it and don't add the DefaultAuthorizer
if none_idx > -1:
del existing_non_authorizer_security[none_idx]
# Existing Authorizer found (defined at Function/Path/Method); use that instead of default
elif existing_authorizer_security:
authorizer_security = existing_authorizer_security
# No existing Authorizer found; use default
else:
security_dict = {}
security_dict[default_authorizer] = []
authorizer_security = [security_dict]
security = existing_non_authorizer_security + authorizer_security
if security:
method_definition['security'] = security
# The first element of the method_definition['security'] should be AWS_IAM
# because authorizer_list = ['AWS_IAM'] is hardcoded above
if 'AWS_IAM' in method_definition['security'][0]:
self.add_awsiam_security_definition()
def set_path_default_apikey_required(self, path):
"""
Add the ApiKey security as required for each method on this path unless ApiKeyRequired
was defined at the Function/Path/Method level. This is intended to be used to set the
apikey security restriction for all api methods based upon the default configured in the
Serverless API.
:param string path: Path name
"""
for method_name, _ in self.get_path(path).items():
# Excluding paramters section
if method_name == "parameters":
continue
normalized_method_name = self._normalize_method_name(method_name)
# It is possible that the method could have two definitions in a Fn::If block.
for method_definition in self.get_method_contents(self.get_path(path)[normalized_method_name]):
# If no integration given, then we don't need to process this definition (could be AWS::NoValue)
if not self.method_definition_has_integration(method_definition):
continue
existing_security = method_definition.get('security', [])
apikey_security_names = set(['api_key', 'api_key_false'])
existing_non_apikey_security = []
existing_apikey_security = []
apikey_security = []
# Split existing security into ApiKey and everything else
# (e.g. sigv4 (AWS_IAM), authorizers, NONE (marker for ignoring default authorizer))
# We want to ensure only a single ApiKey security entry exists while keeping everything else
for security in existing_security:
if apikey_security_names.isdisjoint(security.keys()):
existing_non_apikey_security.append(security)
else:
existing_apikey_security.append(security)
# Check for an existing method level ApiKey setting before applying the default. It would be simpler
# if instead we applied the default first and then simply
# overwrote it if necessary, however, the order in which things get
# applied (Function Api Events first; then Api Resource) complicates it.
# Check if Function/Path/Method specified 'False' for ApiKeyRequired
apikeyfalse_idx = -1
for idx, security in enumerate(existing_apikey_security):
is_none = any(key == 'api_key_false' for key in security.keys())
if is_none:
apikeyfalse_idx = idx
break
# api_key_false was found; remove it and don't add default api_key security setting
if apikeyfalse_idx > -1:
del existing_apikey_security[apikeyfalse_idx]
# No existing ApiKey setting found or it's already set to the default
else:
security_dict = {}
security_dict['api_key'] = []
apikey_security = [security_dict]
security = existing_non_apikey_security + apikey_security
if security != existing_security:
method_definition['security'] = security
def add_auth_to_method(self, path, method_name, auth, api):
"""
Adds auth settings for this path/method. Auth settings currently consist of Authorizers and ApiKeyRequired
but this method will eventually include setting other auth settings such as Resource Policy, etc.
This is used to configure the security for individual functions.
:param string path: Path name
:param string method_name: Method name
:param dict auth: Auth configuration such as Authorizers, ApiKeyRequired, ResourcePolicy
:param dict api: Reference to the related Api's properties as defined in the template.
"""
method_authorizer = auth and auth.get('Authorizer')
if method_authorizer:
self._set_method_authorizer(path, method_name, method_authorizer)
method_apikey_required = auth and auth.get('ApiKeyRequired')
if method_apikey_required is not None:
self._set_method_apikey_handling(path, method_name, method_apikey_required)
def _set_method_authorizer(self, path, method_name, authorizer_name):
"""
Adds the authorizer_name to the security block for each method on this path.
This is used to configure the authorizer for individual functions.
:param string path: Path name
:param string method_name: Method name
:param string authorizer_name: Name of the authorizer to use. Must be a key in the
authorizers param.
"""
normalized_method_name = self._normalize_method_name(method_name)
# It is possible that the method could have two definitions in a Fn::If block.
for method_definition in self.get_method_contents(self.get_path(path)[normalized_method_name]):
# If no integration given, then we don't need to process this definition (could be AWS::NoValue)
if not self.method_definition_has_integration(method_definition):
continue
existing_security = method_definition.get('security', [])
security_dict = {}
security_dict[authorizer_name] = []
authorizer_security = [security_dict]
# This assumes there are no autorizers already configured in the existing security block
security = existing_security + authorizer_security
if security:
method_definition['security'] = security
# The first element of the method_definition['security'] should be AWS_IAM
# because authorizer_list = ['AWS_IAM'] is hardcoded above
if 'AWS_IAM' in method_definition['security'][0]:
self.add_awsiam_security_definition()
def _set_method_apikey_handling(self, path, method_name, apikey_required):
"""
Adds the apikey setting to the security block for each method on this path.
This is used to configure the authorizer for individual functions.
:param string path: Path name
:param string method_name: Method name
:param bool apikey_required: Whether the apikey security is required
"""
normalized_method_name = self._normalize_method_name(method_name)
# It is possible that the method could have two definitions in a Fn::If block.
for method_definition in self.get_method_contents(self.get_path(path)[normalized_method_name]):
# If no integration given, then we don't need to process this definition (could be AWS::NoValue)
if not self.method_definition_has_integration(method_definition):
continue
existing_security = method_definition.get('security', [])
if apikey_required:
# We want to enable apikey required security
security_dict = {}
security_dict['api_key'] = []
apikey_security = [security_dict]
self.add_apikey_security_definition()
else:
# The method explicitly does NOT require apikey and there is an API default
# so let's add a marker 'api_key_false' so that we don't incorrectly override
# with the api default
security_dict = {}
security_dict['api_key_false'] = []
apikey_security = [security_dict]
# This assumes there are no autorizers already configured in the existing security block
security = existing_security + apikey_security
if security != existing_security:
method_definition['security'] = security
def add_request_model_to_method(self, path, method_name, request_model):
"""
Adds request model body parameter for this path/method.
:param string path: Path name
:param string method_name: Method name
:param dict request_model: Model name
"""
model_name = request_model and request_model.get('Model').lower()
model_required = request_model and request_model.get('Required')
normalized_method_name = self._normalize_method_name(method_name)
# It is possible that the method could have two definitions in a Fn::If block.
for method_definition in self.get_method_contents(self.get_path(path)[normalized_method_name]):
# If no integration given, then we don't need to process this definition (could be AWS::NoValue)
if not self.method_definition_has_integration(method_definition):
continue
if self._doc.get('swagger') is not None:
existing_parameters = method_definition.get('parameters', [])
parameter = {
'in': 'body',
'name': model_name,
'schema': {
'$ref': '#/definitions/{}'.format(model_name)
}
}
if model_required is not None:
parameter['required'] = model_required
existing_parameters.append(parameter)
method_definition['parameters'] = existing_parameters
elif self._doc.get("openapi") and \
re.search(SwaggerEditor.get_openapi_version_3_regex(), self._doc["openapi"]) is not None:
method_definition['requestBody'] = {
'content': {
"application/json": {
"schema": {
"$ref": "#/components/schemas/{}".format(model_name)
}
}
}
}
if model_required is not None:
method_definition['requestBody']['required'] = model_required
def add_gateway_responses(self, gateway_responses):
"""
Add Gateway Response definitions to Swagger.
:param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.
"""
self.gateway_responses = self.gateway_responses or {}
for response_type, response in gateway_responses.items():
self.gateway_responses[response_type] = response.generate_swagger()
def add_models(self, models):
"""
Add Model definitions to Swagger.
:param dict models: Dictionary of Model schemas which gets translated
:return:
"""
self.definitions = self.definitions or {}
for model_name, schema in models.items():
model_type = schema.get('type')
model_properties = schema.get('properties')
if not model_type:
raise ValueError("Invalid input. Value for type is required")
if not model_properties:
raise ValueError("Invalid input. Value for properties is required")
self.definitions[model_name.lower()] = schema
def add_resource_policy(self, resource_policy):
"""
Add resource policy definition to Swagger.
:param dict resource_policy: Dictionary of resource_policy statements which gets translated
:return:
"""
if resource_policy is None:
return
custom_statements = resource_policy.get('CustomStatements')
if custom_statements is not None:
if not isinstance(custom_statements, list):
custom_statements = [custom_statements]
self.resource_policy['Version'] = '2012-10-17'
if self.resource_policy.get('Statement') is None:
self.resource_policy['Statement'] = custom_statements
else:
statement = self.resource_policy['Statement']
if isinstance(statement, list):
statement.extend(custom_statements)
else:
statement = [statement]
statement.extend(custom_statements)
self.resource_policy['Statement'] = statement
self._doc[self._X_APIGW_POLICY] = self.resource_policy
@property
def swagger(self):
"""
Returns a **copy** of the Swagger document as a dictionary.
:return dict: Dictionary containing the Swagger document
"""
# Make sure any changes to the paths are reflected back in output
self._doc["paths"] = self.paths
if self.security_definitions:
self._doc["securityDefinitions"] = self.security_definitions
if self.gateway_responses:
self._doc[self._X_APIGW_GATEWAY_RESPONSES] = self.gateway_responses
if self.definitions:
self._doc['definitions'] = self.definitions
return copy.deepcopy(self._doc)
@staticmethod
def is_valid(data):
"""
Checks if the input data is a Swagger document
:param dict data: Data to be validated
:return: True, if data is a Swagger
"""
if bool(data) and isinstance(data, dict) and isinstance(data.get('paths'), dict):
if bool(data.get("swagger")):
return True
elif bool(data.get("openapi")):
return re.search(SwaggerEditor.get_openapi_version_3_regex(), data["openapi"]) is not None
return False
return False
@staticmethod
def gen_skeleton():
"""
Method to make an empty swagger file, with just some basic structure. Just enough to pass validator.
:return dict: Dictionary of a skeleton swagger document
"""
return {
'swagger': '2.0',
'info': {
'version': '1.0',
'title': ref('AWS::StackName')
},
'paths': {
}
}
@staticmethod
def _normalize_method_name(method):
"""
Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods
like "ANY"
NOTE: Always normalize before using the `method` value passed in as input
:param string method: Name of the HTTP Method
:return string: Normalized method name
"""
if not method or not isinstance(method, string_types):
return method
method = method.lower()
if method == 'any':
return SwaggerEditor._X_ANY_METHOD
else:
return method
@staticmethod
def get_openapi_versions_supported_regex():
openapi_version_supported_regex = r"\A[2-3](\.\d)(\.\d)?$"
return openapi_version_supported_regex
@staticmethod
def get_openapi_version_3_regex():
openapi_version_3_regex = r"\A3(\.\d)(\.\d)?$"
return openapi_version_3_regex