serverless-application-model icon indicating copy to clipboard operation
serverless-application-model copied to clipboard

cors: true

Open nalbion opened this issue 10 years ago • 37 comments

One thing that I like about serverless.com is that CORS can be enabled for an endpoint in one short line:

cors: true

Currently, to enable CORS using x-amazon-apigateway-integration, it is necessary to:

  • add a header to each response:
responses:
        '200':
          description: Request successful
          headers:
            Access-Control-Allow-Origin:
              type: string
          schema:
            $ref: '#/definitions/Success'
        '400':
          description: Authentication failed
          headers:
            Access-Control-Allow-Origin:
              type: string
          schema:
            $ref: '#/definitions/Error'
  • add responseParameters in x-amazon-apigateway-integration:
default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Origin : "'*'"
          '.*"status":400.*':
            statusCode: '400'
            responseParameters:
              method.response.header.Access-Control-Allow-Origin : "'*'"
  • add a massive options section:
options:
      summary: CORS support
      description: |
        Enable CORS by returning correct headers
      responses:
        200:
          description: Default response for CORS method
          headers:
            Access-Control-Allow-Headers:
              type: string
            Access-Control-Allow-Methods:
              type: string
            Access-Control-Allow-Origin:
              type: string
      x-amazon-apigateway-integration:
        type: mock
        requestTemplates:
          application/json: |
            {"statusCode" : 200}
        responses:
          "default":
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Headers : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
              method.response.header.Access-Control-Allow-Methods : "'*'"
              method.response.header.Access-Control-Allow-Origin : "'*'"
            responseTemplates:
              application/json: |
                {}

...it'd be great if Transform: AWS::Serverless-2016-10-31 could transform the swagger schema, automatically adding all of this if cors: true is present in the CloudFormation object

nalbion avatar Nov 24 '16 04:11 nalbion

I like this. This would be doable for implicit APIs specified in the Events section of a Function resource, because CloudFormation generates the swagger for you. For APIs created using AWS::Serverless::API resource, users will supply their own Swagger file in S3. The logic that parses Serverless resources does not have the access to read and manipulate S3 files.

sanathkr avatar Nov 28 '16 18:11 sanathkr

Does the former allow you to save a local copy of the swagger schema, so that we may merge/cross-check the generated and documenting swagger schema?

nalbion avatar Nov 28 '16 22:11 nalbion

Yeah. After you create the stack you can download the generated template using CloudFormation get-template command. It will have the Swagger template embedded in it

sanathkr avatar Nov 29 '16 20:11 sanathkr

This could be somewhat DRYed by defining a patterned object at the root of the Swagger file:

x-amazon-apigateway-integration-cors-headers:
  method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
  method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
  method.response.header.Access-Control-Allow-Origin: "'*'"

After that, these headers can be referenced in x-amazon-apigateway-integration: through

responseParameters:
  allOf:
    - $ref: '#/x-amazon-apigateway-integration-cors-headers'

dinvlad avatar Nov 30 '16 17:11 dinvlad

Just confirming that for this feature request, we're talking about entirely eliminating the need for users to create their own Swagger files to enable CORS. We shouldn't force users to explicitly adopt Swagger if they don't want to. (It's fine if a Swagger file is autogenerated under the covers, as long as users don't have to manually create a Swagger file.)

rabowskyb avatar Jan 04 '17 16:01 rabowskyb

Personally, I'm a fan of Swagger, but x-amazon-apigateway-integration with CORS adds too much noise.

nalbion avatar Jan 10 '17 11:01 nalbion

It'd be nice to keep an option to specify a Swagger template, but without all the extra clutter. One case we need to use Swagger for is for input validation, where we'd like to make sure the shape of the API is preserved between that defined in a SAM template and that specified explicitly in Swagger (with the latter having extra information about input parameter types etc.)

Could there be an option to define a "template template" Swagger, with all of API Gateway integration parameters specified over a ${SOME_VAR} syntax that are then dynamically expanded during processing of the SAM template? This will be then very similar to how currently the SAM template is itself "expanded" into a normal CloudFormation template during packaging.

dinvlad avatar Jan 10 '17 18:01 dinvlad

To echo what @rabowskyb said, it would be nice to have a cors: true option in the sam.yml file itself. I'm using SAM to build a lot of microservices and a swagger file seems overkill for something that literally only has one endpoint. [edit: to be fair, I haven't spent any time trying to learn swagger, so it may not be all that difficult... but I still think a SAM-only version would be much appreciated]

frehner avatar Jan 31 '17 21:01 frehner

Here is a proposal of how this could work. API Event will get a new property called Cors. Here are two ways to use it:

Shorthand

Type: AWS::Serverless::Function
Properties:
  Runtime: ...
  Events:
     GetApi:
         Type: Api
         Properties:
              Cors: "*"
             Method: GET
             Path: /foo

     PostApi:
         Type: Api
         Properties:
              Cors: "http://example.com"
             Method: POST
             Path: /foo

This will generate CORS headers automatically, for each Path+Method combo and set Allow-Origin to "*". The value of Cors property is a list of origins you want to allow. Allow-Headers is always set to "*".

Long Form

Type: AWS::Serverless::Function
Properties:
  Runtime: ...
  Events:
     GetApi:
         Type: Api
         Properties:
              Cors: 
                  AllowOrigin: "List of origins"
                  AllowHeaders: "List of allowed headers"
             Method: GET
             Path: /foo

     PostApi:
         Type: Api
         Properties:
              Cors: 
                  AllowOrigin: "List of origins"
                  AllowHeaders: "List of allowed headers"
             Method: POST
             Path: /foo

This will generate CORS headers automatically, for each Path+Method combo and set Allow-Origin and Allow-Headers to whatever value that was specified.

Would this address use-cases you guys are going after?

Unfortunately we can't add the same functionality to AWS::Serverless::Api property because the translator converting SAM to CloudFormation cannot read and modify your Swagger file.

sanathkr avatar Feb 03 '17 23:02 sanathkr

So both the short form and long form will be offered? Would it be possible to allow use of wildcards in the list of origins, for example "*.example.com"?

Overall, your proposal above appears to eliminate the need to use swagger to enable CORS, while providing a degree of flexibility to specify allowed origins and headers. This supports my use case of webapps backed by serverless backends deployed with SAM.

rabowskyb avatar Feb 04 '17 00:02 rabowskyb

yes, both forms will be available. SAM wouldn't touch the value of AllowOrigin you specify. So you can write anything that HTTP will accept

sanathkr avatar Feb 04 '17 00:02 sanathkr

Is there any ETA for this feature? This will make the use of SAM so much easier...

hoegertn avatar Feb 20 '17 18:02 hoegertn

Any updates really want this feature?

Did a comparison between serverless framework and SAM and the only reason serverless has less lines in yaml is due to the verbose inline swagger definitions.

gertjvr avatar Mar 21 '17 03:03 gertjvr

Is there any update regarding this ... i think most of us are desperately waiting for this feature.

ahmadsn26 avatar Jun 14 '17 04:06 ahmadsn26

May we also ask to be able to specify allowed methods per-resource? E.g. some resources may only have Get or only Post, while others a broader spectrum (e.g. Get, Patch, and Delete). It wouldn't make sense to return all "legal" verbs at once API-wide when only some of them are implemented, depending on resource. Unfortunately, doing that is common in other frameworks (e.g. Express), even though it goes against the RFC and the intended purpose of the Options request.

dinvlad avatar Jun 14 '17 06:06 dinvlad

@dinvlad we can already infer the method name from the API definition and apply Cors only on it. Doable.

As for ETA, I don't have a concrete date yet. We have started the implementation. So this is definitely happening :-)

sanathkr avatar Jun 28 '17 19:06 sanathkr

Awesome, great to hear Cors support is on the roadmap. Any further updates on ETA?

john avatar Jul 11 '17 17:07 john

+1 Any updates maybe? or at least an example how to do this in SAM before it is implemented

lskrajny avatar Jul 26 '17 09:07 lskrajny

Quick update: We are almost done with the implementation. We will rollout this change shortly after QA. A couple more weeks, may be. Hang tight :-)

sanathkr avatar Jul 26 '17 16:07 sanathkr

Any update @sanathkr ?

We've implemented a swagger file to get around for the time being but are keen to remove it.

mbailey avatar Aug 17 '17 01:08 mbailey