From abd309a7aeb0fdc9e5713d427a5e5cdce27cde7f Mon Sep 17 00:00:00 2001 From: Shreya Gangishetty Date: Thu, 2 Jan 2020 15:55:09 -0800 Subject: [PATCH 1/2] Revert "fix: allow Authorizer: NONE when using custom swagger (#1211)" This reverts commit fefc61f49de49ba69d6fbc1fccefc6e1dbe3a8d3. --- samtranslator/model/eventsources/push.py | 175 ++++++++---------- .../api_with_swagger_authorizer_none.yaml | 117 ------------ tests/translator/test_translator.py | 1 - 3 files changed, 82 insertions(+), 211 deletions(-) delete mode 100644 tests/translator/input/api_with_swagger_authorizer_none.yaml diff --git a/samtranslator/model/eventsources/push.py b/samtranslator/model/eventsources/push.py index 82b7ddeb1..11a78cf7d 100644 --- a/samtranslator/model/eventsources/push.py +++ b/samtranslator/model/eventsources/push.py @@ -556,7 +556,8 @@ def to_cloudformation(self, **kwargs): resources.extend(self._get_permissions(kwargs)) explicit_api = kwargs["explicit_api"] - self._add_swagger_integration(explicit_api, function) + if explicit_api.get("__MANAGE_SWAGGER"): + self._add_swagger_integration(explicit_api, function) return resources @@ -619,21 +620,19 @@ def _add_swagger_integration(self, api, function): ) editor = SwaggerEditor(swagger_body) - if api.get("__MANAGE_SWAGGER"): - if editor.has_integration(self.Path, self.Method): - # Cannot add the Lambda Integration, if it is already present - raise InvalidEventException( - self.relative_id, - 'API method "{method}" defined multiple times for path "{path}".'.format( - method=self.Method, path=self.Path - ), - ) - condition = None - if CONDITION in function.resource_attributes: - condition = function.resource_attributes[CONDITION] + if editor.has_integration(self.Path, self.Method): + # Cannot add the Lambda Integration, if it is already present + raise InvalidEventException( + self.relative_id, + 'API method "{method}" defined multiple times for path "{path}".'.format( + method=self.Method, path=self.Path)) - editor.add_lambda_integration(self.Path, self.Method, uri, self.Auth, api.get("Auth"), condition=condition) + condition = None + if CONDITION in function.resource_attributes: + condition = function.resource_attributes[CONDITION] + + editor.add_lambda_integration(self.Path, self.Method, uri, self.Auth, api.get("Auth"), condition=condition) if self.Auth: method_authorizer = self.Auth.get("Authorizer") @@ -690,100 +689,90 @@ def _add_swagger_integration(self, api, function): ) if method_authorizer or apikey_required_setting is not None: - if editor.has_path(self.Path): - editor.add_auth_to_method(api=api, path=self.Path, method_name=self.Method, auth=self.Auth) + editor.add_auth_to_method(api=api, path=self.Path, method_name=self.Method, auth=self.Auth) + + if self.Auth.get('ResourcePolicy'): + resource_policy = self.Auth.get('ResourcePolicy') + editor.add_resource_policy(resource_policy=resource_policy, + path=self.Path, api_id=self.RestApiId.get('Ref'), stage=self.Stage) + + if self.RequestModel: + method_model = self.RequestModel.get('Model') + + if method_model: + api_models = api.get('Models') + if not api_models: + raise InvalidEventException( + self.relative_id, + 'Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] ' + 'because the related API does not define any Models.'.format( + model=method_model, method=self.Method, path=self.Path)) + + if not api_models.get(method_model): + raise InvalidEventException( + self.relative_id, + 'Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] ' + 'because it wasn\'t defined in the API\'s Models.'.format( + model=method_model, method=self.Method, path=self.Path)) + + editor.add_request_model_to_method(path=self.Path, method_name=self.Method, + request_model=self.RequestModel) + + if self.RequestParameters: + + default_value = { + 'Required': False, + 'Caching': False + } - if self.Auth.get("ResourcePolicy"): - resource_policy = self.Auth.get("ResourcePolicy") - editor.add_resource_policy( - resource_policy=resource_policy, path=self.Path, api_id=self.RestApiId.get("Ref"), stage=self.Stage - ) - if api.get("__MANAGE_SWAGGER"): - if self.RequestModel: - method_model = self.RequestModel.get("Model") + parameters = [] + for parameter in self.RequestParameters: + + if isinstance(parameter, dict): + + parameter_name, parameter_value = next(iter(parameter.items())) - if method_model: - api_models = api.get("Models") - if not api_models: + if not re.match('method\.request\.(querystring|path|header)\.', parameter_name): raise InvalidEventException( self.relative_id, - "Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] " - "because the related API does not define any Models.".format( - model=method_model, method=self.Method, path=self.Path - ), - ) + "Invalid value for 'RequestParameters' property. Keys must be in the format " + "'method.request.[querystring|path|header].{value}', " + "e.g 'method.request.header.Authorization'.") - if not api_models.get(method_model): + if not isinstance(parameter_value, dict) or not all(key in REQUEST_PARAMETER_PROPERTIES + for key in parameter_value.keys()): raise InvalidEventException( self.relative_id, - "Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] " - "because it wasn't defined in the API's Models.".format( - model=method_model, method=self.Method, path=self.Path - ), + "Invalid value for 'RequestParameters' property. Values must be an object, " + "e.g { Required: true, Caching: false }" ) - editor.add_request_model_to_method( - path=self.Path, method_name=self.Method, request_model=self.RequestModel - ) - - if self.RequestParameters: - - default_value = {"Required": False, "Caching": False} + settings = default_value.copy() + settings.update(parameter_value) + settings.update({'Name': parameter_name}) - parameters = [] - for parameter in self.RequestParameters: + parameters.append(settings) - if isinstance(parameter, dict): - - parameter_name, parameter_value = next(iter(parameter.items())) - - if not re.match("method\.request\.(querystring|path|header)\.", parameter_name): - raise InvalidEventException( - self.relative_id, - "Invalid value for 'RequestParameters' property. Keys must be in the format " - "'method.request.[querystring|path|header].{value}', " - "e.g 'method.request.header.Authorization'.", - ) - - if not isinstance(parameter_value, dict) or not all( - key in REQUEST_PARAMETER_PROPERTIES for key in parameter_value.keys() - ): - raise InvalidEventException( - self.relative_id, - "Invalid value for 'RequestParameters' property. Values must be an object, " - "e.g { Required: true, Caching: false }", - ) - - settings = default_value.copy() - settings.update(parameter_value) - settings.update({"Name": parameter_name}) - - parameters.append(settings) - - elif isinstance(parameter, string_types): - if not re.match("method\.request\.(querystring|path|header)\.", parameter): - raise InvalidEventException( - self.relative_id, - "Invalid value for 'RequestParameters' property. Keys must be in the format " - "'method.request.[querystring|path|header].{value}', " - "e.g 'method.request.header.Authorization'.", - ) + elif isinstance(parameter, string_types): + if not re.match('method\.request\.(querystring|path|header)\.', parameter): + raise InvalidEventException( + self.relative_id, + "Invalid value for 'RequestParameters' property. Keys must be in the format " + "'method.request.[querystring|path|header].{value}', " + "e.g 'method.request.header.Authorization'.") - settings = default_value.copy() - settings.update({"Name": parameter}) + settings = default_value.copy() + settings.update({'Name': parameter}) - parameters.append(settings) + parameters.append(settings) - else: - raise InvalidEventException( - self.relative_id, - "Invalid value for 'RequestParameters' property. " - "Property must be either a string or an object", - ) + else: + raise InvalidEventException( + self.relative_id, + "Invalid value for 'RequestParameters' property. Property must be either a string or an object") - editor.add_request_parameters_to_method( - path=self.Path, method_name=self.Method, request_parameters=parameters - ) + editor.add_request_parameters_to_method(path=self.Path, method_name=self.Method, + request_parameters=parameters) api["DefinitionBody"] = editor.swagger diff --git a/tests/translator/input/api_with_swagger_authorizer_none.yaml b/tests/translator/input/api_with_swagger_authorizer_none.yaml deleted file mode 100644 index eb0ae32be..000000000 --- a/tests/translator/input/api_with_swagger_authorizer_none.yaml +++ /dev/null @@ -1,117 +0,0 @@ -Resources: - MyApiWithCognitoAuth: - Type: "AWS::Serverless::Api" - Properties: - StageName: Prod - Auth: - Authorizers: - MyCognitoAuth: - UserPoolArn: !GetAtt MyUserPool.Arn - DefaultAuthorizer: MyCognitoAuth - - MyApiWithLambdaTokenAuth: - Type: "AWS::Serverless::Api" - Properties: - StageName: Prod - Auth: - Authorizers: - MyLambdaTokenAuth: - FunctionArn: !GetAtt MyAuthFn.Arn - DefaultAuthorizer: MyLambdaTokenAuth - - MyApiWithLambdaRequestAuth: - Type: "AWS::Serverless::Api" - Properties: - StageName: Prod - DefinitionBody: - swagger: 2.0 - info: - version: '1.0' - title: !Ref AWS::StackName - schemes: - - https - paths: - "/lambda-request": - get: - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyFn.Arn}/invocations - passthroughBehavior: when_no_match - responses: {} - Auth: - Authorizers: - MyLambdaRequestAuth: - FunctionPayloadType: REQUEST - FunctionArn: !GetAtt MyAuthFn.Arn - Identity: - Headers: - - Authorization1 - DefaultAuthorizer: MyLambdaRequestAuth - - MyAuthFn: - Type: AWS::Serverless::Function - Properties: - InlineCode: | - exports.handler = async (event) => { - return { - statusCode: 200, - body: JSON.stringify(event), - headers: {} - } - } - Handler: index.handler - Runtime: nodejs8.10 - - MyFn: - Type: AWS::Serverless::Function - Properties: - InlineCode: | - exports.handler = async (event) => { - return { - statusCode: 200, - body: JSON.stringify(event), - headers: {} - } - } - Handler: index.handler - Runtime: nodejs8.10 - Events: - Cognito: - Type: Api - Properties: - RestApiId: !Ref MyApiWithCognitoAuth - Method: get - Auth: - Authorizer: NONE - Path: /cognito - LambdaToken: - Type: Api - Properties: - RestApiId: !Ref MyApiWithLambdaTokenAuth - Method: get - Auth: - Authorizer: NONE - Path: /lambda-token - LambdaRequest: - Type: Api - Properties: - RestApiId: !Ref MyApiWithLambdaRequestAuth - Auth: - Authorizer: NONE - Method: get - Path: /lambda-request - - MyUserPool: - Type: AWS::Cognito::UserPool - Properties: - UserPoolName: UserPoolName - Policies: - PasswordPolicy: - MinimumLength: 8 - UsernameAttributes: - - email - Schema: - - AttributeDataType: String - Name: email - Required: false \ No newline at end of file diff --git a/tests/translator/test_translator.py b/tests/translator/test_translator.py index e1480b183..83d9717ca 100644 --- a/tests/translator/test_translator.py +++ b/tests/translator/test_translator.py @@ -268,7 +268,6 @@ class TestTranslatorEndToEnd(TestCase): "api_with_apikey_required", "api_with_path_parameters", "function_with_event_source_mapping", - "api_with_swagger_authorizer_none", "function_with_event_dest", "function_with_event_dest_basic", "function_with_event_dest_conditional", From 10c38d533dee9cd388e96ef048636154aa9a92db Mon Sep 17 00:00:00 2001 From: Shreya Gangishetty Date: Thu, 2 Jan 2020 16:05:15 -0800 Subject: [PATCH 2/2] fix: update black formatting --- samtranslator/model/eventsources/push.py | 74 ++++++++++++++---------- 1 file changed, 42 insertions(+), 32 deletions(-) diff --git a/samtranslator/model/eventsources/push.py b/samtranslator/model/eventsources/push.py index 11a78cf7d..442a97a15 100644 --- a/samtranslator/model/eventsources/push.py +++ b/samtranslator/model/eventsources/push.py @@ -626,7 +626,9 @@ def _add_swagger_integration(self, api, function): raise InvalidEventException( self.relative_id, 'API method "{method}" defined multiple times for path "{path}".'.format( - method=self.Method, path=self.Path)) + method=self.Method, path=self.Path + ), + ) condition = None if CONDITION in function.resource_attributes: @@ -691,39 +693,42 @@ def _add_swagger_integration(self, api, function): if method_authorizer or apikey_required_setting is not None: editor.add_auth_to_method(api=api, path=self.Path, method_name=self.Method, auth=self.Auth) - if self.Auth.get('ResourcePolicy'): - resource_policy = self.Auth.get('ResourcePolicy') - editor.add_resource_policy(resource_policy=resource_policy, - path=self.Path, api_id=self.RestApiId.get('Ref'), stage=self.Stage) + if self.Auth.get("ResourcePolicy"): + resource_policy = self.Auth.get("ResourcePolicy") + editor.add_resource_policy( + resource_policy=resource_policy, path=self.Path, api_id=self.RestApiId.get("Ref"), stage=self.Stage + ) if self.RequestModel: - method_model = self.RequestModel.get('Model') + method_model = self.RequestModel.get("Model") if method_model: - api_models = api.get('Models') + api_models = api.get("Models") if not api_models: raise InvalidEventException( self.relative_id, - 'Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] ' - 'because the related API does not define any Models.'.format( - model=method_model, method=self.Method, path=self.Path)) + "Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] " + "because the related API does not define any Models.".format( + model=method_model, method=self.Method, path=self.Path + ), + ) if not api_models.get(method_model): raise InvalidEventException( self.relative_id, - 'Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] ' - 'because it wasn\'t defined in the API\'s Models.'.format( - model=method_model, method=self.Method, path=self.Path)) - - editor.add_request_model_to_method(path=self.Path, method_name=self.Method, - request_model=self.RequestModel) + "Unable to set RequestModel [{model}] on API method [{method}] for path [{path}] " + "because it wasn't defined in the API's Models.".format( + model=method_model, method=self.Method, path=self.Path + ), + ) + + editor.add_request_model_to_method( + path=self.Path, method_name=self.Method, request_model=self.RequestModel + ) if self.RequestParameters: - default_value = { - 'Required': False, - 'Caching': False - } + default_value = {"Required": False, "Caching": False} parameters = [] for parameter in self.RequestParameters: @@ -732,47 +737,52 @@ def _add_swagger_integration(self, api, function): parameter_name, parameter_value = next(iter(parameter.items())) - if not re.match('method\.request\.(querystring|path|header)\.', parameter_name): + if not re.match("method\.request\.(querystring|path|header)\.", parameter_name): raise InvalidEventException( self.relative_id, "Invalid value for 'RequestParameters' property. Keys must be in the format " "'method.request.[querystring|path|header].{value}', " - "e.g 'method.request.header.Authorization'.") + "e.g 'method.request.header.Authorization'.", + ) - if not isinstance(parameter_value, dict) or not all(key in REQUEST_PARAMETER_PROPERTIES - for key in parameter_value.keys()): + if not isinstance(parameter_value, dict) or not all( + key in REQUEST_PARAMETER_PROPERTIES for key in parameter_value.keys() + ): raise InvalidEventException( self.relative_id, "Invalid value for 'RequestParameters' property. Values must be an object, " - "e.g { Required: true, Caching: false }" + "e.g { Required: true, Caching: false }", ) settings = default_value.copy() settings.update(parameter_value) - settings.update({'Name': parameter_name}) + settings.update({"Name": parameter_name}) parameters.append(settings) elif isinstance(parameter, string_types): - if not re.match('method\.request\.(querystring|path|header)\.', parameter): + if not re.match("method\.request\.(querystring|path|header)\.", parameter): raise InvalidEventException( self.relative_id, "Invalid value for 'RequestParameters' property. Keys must be in the format " "'method.request.[querystring|path|header].{value}', " - "e.g 'method.request.header.Authorization'.") + "e.g 'method.request.header.Authorization'.", + ) settings = default_value.copy() - settings.update({'Name': parameter}) + settings.update({"Name": parameter}) parameters.append(settings) else: raise InvalidEventException( self.relative_id, - "Invalid value for 'RequestParameters' property. Property must be either a string or an object") + "Invalid value for 'RequestParameters' property. Property must be either a string or an object", + ) - editor.add_request_parameters_to_method(path=self.Path, method_name=self.Method, - request_parameters=parameters) + editor.add_request_parameters_to_method( + path=self.Path, method_name=self.Method, request_parameters=parameters + ) api["DefinitionBody"] = editor.swagger