Origin 'https://docs.domain.tld' is therefore not allowed access

lambda

#1

Hello,

I have the following serverless.yml

service: mims

plugins:
  - serverless-s3-sync
  - serverless-domain-manager

package:
 exclude:
   - ./**
 include:
   - ./bin/status

provider:
  name: aws
  runtime: go1.x
  stage: ${opt:stage}
  iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:*
      Resource: "*"
    - Effect: Allow
      Action:
        - apigateway:*
      Resource: "arn:aws:apigateway:*::/*"
    - Effect: Allow
      Action:
        - execute-api:Invoke
      Resource: "arn:aws:execute-api:*:*:*"
    - Effect: Allow
      Action:
        - logs:CreateLogGroup
        - logs:CreateLogStream
        - logs:DescribeLogGroups
        - logs:DescribeLogStreams
        - logs:PutLogEvents
        - logs:GetLogEvents
        - logs:FilterLogEvents
      Resource: "*"

custom:
  s3Sync:
    - bucketName: ${file(./config.yml):${opt:stage}.MBM_MIMS_BUCKET}
      localDir: public
  customDomain:
    domainName: ${file(./config.yml):${opt:stage}.DOMAIN_ROOT}
    basePath: ''
    stage: ${self:provider.stage}
    createRoute53Record: true

functions:
  status:
    handler: bin/status
    description: Status/healthcheck function for MIMS API
    memorySize: 128
    environment:
      API: ${file(./config.yml):${opt:stage}.API}
      MBM_MIMS_BUCKET: ${file(./config.yml):${opt:stage}.MBM_MIMS_BUCKET}
      REGION: ${file(./config.yml):${opt:stage}.REGION}
    events:
      - http:
          path: status
          method: get
          cors: true
    timeout: 30

resources:
  Resources:
    mimsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${file(./config.yml):${opt:stage}.MBM_MIMS_BUCKET}
        AccessControl: PublicRead
        WebsiteConfiguration:
          ErrorDocument: index.html
          IndexDocument: index.html
        CorsConfiguration:
          CorsRules:
          - AllowedMethods:
            - GET
            - POST
            - PUT
            - HEAD
            AllowedOrigins:
            - "*"
            AllowedHeaders:
            - "*"
    mimsBucketPolicy:
      Type: AWS::S3::BucketPolicy
      Properties:
        Bucket:
          Ref: mimsBucket
        PolicyDocument:
          Statement:
            - Sid: PublicReadGetObject
              Effect: Allow
              Principal: "*"
              Action:
              - s3:GetObject
              Resource:
                Fn::Join: [
                  "", [
                    "arn:aws:s3:::",
                    {
                      "Ref": "mimsBucket"
                    },
                    "/*"
                  ]
                ]
    CDN:
      Type: "AWS::CloudFront::Distribution"
      Properties:
        DistributionConfig:
          ViewerCertificate:
            AcmCertificateArn: ${file(./config.yml):${opt:stage}.CERTIFICATE_ARN}
            SslSupportMethod: sni-only
          Enabled: true
          HttpVersion: http2
          # IsIPV6Enabled: true
          # not supported by cloudformation
          # https://forums.aws.amazon.com/thread.jspa?messageID=764293
          Aliases: ${file(./config.yml):${opt:stage}.DOMAIN_ALIASES}
          DefaultRootObject: index.html
          Origins:
            - DomainName: {"Fn::Join": ["", ["${file(./config.yml):${opt:stage}.MBM_MIMS_BUCKET}", ".", "s3.amazonaws.com"]]}
              # trint-player-prod-us-east-1.s3.amazonaws.com
              Id: {"Fn::Join": ["", ["S3", "-", "${file(./config.yml):${opt:stage}.MBM_MIMS_BUCKET}"]]}
              CustomOriginConfig:
                HTTPSPort: 443
                OriginProtocolPolicy: http-only
          DefaultCacheBehavior:
            ViewerProtocolPolicy: redirect-to-https # allow-all
            TargetOriginId: {"Fn::Join": ["", ["S3", "-", "${file(./config.yml):${opt:stage}.MBM_MIMS_BUCKET}"]]}
            AllowedMethods:
              - GET
              - HEAD
            Compress: true
            DefaultTTL: 30
            MinTTL: 10
            ForwardedValues:
              QueryString: true

in docs.domain.tld i have setup the swagger UI dist files https://github.com/swagger-api/swagger-ui/tree/master/dist

and i am pushing these files to s3 using the serverless-s3-sync and i have setup a custom domain as per https://serverless.com/blog/serverless-api-gateway-domain/

all this works fine and i am able to run:

curl -X GET "https://api.domain.tld/status" -H "accept: application/json"

but when I try the same command from the swagger UI, i get:

Failed to load https://api.domain.tld/status: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://docs.domain.tld’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

How do i enable cors so that https://docs.domain.tld is allowed access to https://api.domain.tld`?

Any advice is much appreciated


#2

I had to set the

// Handler is our lambda handler invoked by the `lambda.Start` function call
func Handler(ctx context.Context) (Response, error) {
	var buf bytes.Buffer

	body, err := json.Marshal(map[string]interface{}{
		"message": "Serverless endpoint",
	})
	if err != nil {
		return Response{StatusCode: 404}, err
	}
	json.HTMLEscape(&buf, body)

	resp := Response{
		StatusCode:      200,
		IsBase64Encoded: false,
		Body:            buf.String(),
		Headers: map[string]string{
			"Content-Type":					"application/json",
			"Access-Control-Allow-Origin":	"https://docs.domain.tld",
		},
	}

	return resp, nil
}