aws-amplify / amplify-cli

The AWS Amplify CLI is a toolchain for simplifying serverless web and mobile development.
Apache License 2.0
2.81k stars 821 forks source link

API Gateway CORS is blocking localhost access #8019

Closed andrecasal closed 2 years ago

andrecasal commented 3 years ago

Before opening, please confirm:

How did you install the Amplify CLI?

npm i -g @aws-amplify/cli

If applicable, what version of Node.js are you using?

16.6.0

Amplify CLI Version

5.3.0

What operating system are you using?

macOS 11.5.2

Amplify Categories

api

Amplify Commands

add, push, update

Describe the bug

After running amplify update API and adding access restrictions to the API endpoint for only authenticated users, I can no longer access the lambda function from my localhost.

After running this:

Screenshot 2021-08-24 at 11 35 10

This happens:

Screenshot 2021-08-24 at 11 35 38

Expected behavior

I would expect that place to edit the CORS policies to be obvious or easier to find. I've searched the AWS API Gateway console but I found nothing related to CORS policies anywhere.

Reproduction steps

  1. Run amplify ad api and add some lambda function
  2. Refer to the "Describe the bug section" and run that command

GraphQL schema(s)

```graphql # Put schemas below this line ```

Log output

``` # Put your logs below this line ```

Additional information

No response

andrecasal commented 3 years ago

Could this be a CloudFront problem?

Screenshot 2021-08-24 at 12 03 20
RoniqueRicketts commented 3 years ago

I have the same issue I am on the same version on Amplify (the same issue was on the previous version also). I am on Windows 10 OS. What I found out for this issue so far:

  1. The request never reaches the Lambda functions connected to the API.
  2. If I turn off Authenticated users only I am able to hit the open API with the same failed frontend request from before and get a 200 response.
  3. Disabling the IAM Feature off the endpoint makes the API accessible which gives me 200 response but the API is not protected.
  4. If I update the policy that controls the authRole to full access I get the same error.
andrecasal commented 3 years ago

This is weird because the preflight request says I can POST from any URL:

Screenshot 2021-08-25 at 12 00 47

But the request itself fails with AccessDeniedException:

Screenshot 2021-08-25 at 12 02 51
josefaidt commented 3 years ago

Hey y'all :wave: after restricting access to the API route, I was able to add the CORS headers (or uncomment what's provided from the templates) to mitigate this issue

exports.handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    //  Uncomment below to enable CORS requests
+   headers: {
+     'Access-Control-Allow-Origin': '*',
+     'Access-Control-Allow-Headers': '*',
+   },
    body: JSON.stringify('Hello from Lambda!'),
  }
  return response
}

and my sample app.js file in a Next.js app making the call with authentication

// src/pages/_app.js
import { useEffect, useState } from 'react'
import { Amplify, API } from 'aws-amplify'
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'
import config from '../aws-exports.js'

Amplify.configure(config)

async function get() {
  const apiName = 'api8019'
  const path = '/hello'
  const myInit = {
    response: true,
  }

  return API.get(apiName, path, myInit)
    .then((response) => {
      console.log('got response', response)
      return response
    })
    .catch((error) => {
      console.log('got error', error)
      return error
    })
}

function App() {
  const [response, setResponse] = useState()
  const [isLoading, setIsLoading] = useState(false)
  async function getResponse() {
    setIsLoading(true)
    setResponse(await get())
    setIsLoading(false)
  }
  useEffect(() => {
    getResponse()
  }, [])
  return (
    <div>
      <AmplifySignOut />
      <button onClick={getResponse}>refresh</button>
      {isLoading && <span>Loading...</span>}
      <code>
        <pre>{JSON.stringify(response, null, 2)}</pre>
      </code>
    </div>
  )
}

export default withAuthenticator(App)
andrecasal commented 3 years ago

@josefaidt I've tried that but my request is being blocked before it hits the function. I know that because when I remove authorization, I can see logs for the Lambda function and when I add authorization and get the error, those logs don't show up.

How did you add the API and function? Did you run amplify add api?

josefaidt commented 3 years ago

Hey @andrecasal yes I used amplify add api and added a GET and POST route.

  1. add the API with an unsecured route to confirm no CORS issues

    > amplify add api
    ? Please select from one of the below mentioned services: REST
    ? Provide a friendly name for your resource to be used as a label for this category in the project: api8019
    ? Provide a path (e.g., /book/{isbn}): /hello
    ? Choose a Lambda source Create a new Lambda function
    ? Provide an AWS Lambda function name: 8019hello
    ? Choose the runtime that you want to use: NodeJS
    ? Choose the function template that you want to use: Hello World
  2. secure the route

    > amplify update api
    ? Please select from one of the below mentioned services: REST
    ? Please select the REST API you would want to update api8019
    ? What would you like to do Update path
    ? Please select the path you would want to edit /hello
    ? Provide a path (e.g., /book/{isbn}): /hello
    ? Choose a Lambda source Use a Lambda function already added in the current Amplify project
    ? Choose the Lambda function to invoke by this path 8019hello
    ? Restrict API access Yes
    ? Who should have access? Authenticated users only
    ? What kind of access do you want for Authenticated users? read
  3. modify the Lambda handler to include CORS headers

    exports.handler = async (event) => {
      // TODO implement
      const response = {
        statusCode: 200,
        //  Uncomment below to enable CORS requests
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': '*',
        },
        body: JSON.stringify('Hello from Lambda!'),
      }
      return response
    }
  4. add a POST route

    > amplify update api
    ? Please select from one of the below mentioned services: REST
    ? Please select the REST API you would want to update api8019
    ? What would you like to do Add another path
    ? Provide a path (e.g., /book/{isbn}): /hello-post
    ? Choose a Lambda source Create a new Lambda function
    ? Provide an AWS Lambda function name: 8019hellopost
    ? Choose the runtime that you want to use: NodeJS
    ? Choose the function template that you want to use: Hello World
    ...
    ? Restrict API access Yes
    ? Who should have access? Authenticated users only
    ? What kind of access do you want for Authenticated users? create
  5. modify the Lambda handler to respond to POST requests and include CORS headers

    exports.handler = async (event) => {
      // TODO implement
      const { name } = JSON.parse(event.body)
      const body = JSON.stringify(`Hello, ${name}!`)
      const response = {
        statusCode: 200,
        //  Uncomment below to enable CORS requests
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': '*',
        },
        body,
      }
      return response
    }
  6. run amplify push

  7. in my frontend Next.js _app.js file:

    code ```js import { useEffect, useState } from 'react' import { Amplify, API, Auth } from 'aws-amplify' import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react' import config from '../aws-exports.js' Amplify.configure(config) async function get() { const apiName = 'api8019' const path = '/hello' const myInit = { // response: true, } return API.get(apiName, path, myInit) .then((response) => { console.log('got response', response) return response }) .catch((error) => { console.log('got error', error) return error }) } async function post() { const apiName = 'api8019' const path = '/hello-post' const myInit = { // response: true, body: { name: 'World' }, } return API.post(apiName, path, myInit) .then((response) => { console.log('got response', response) return response }) .catch((error) => { console.log('got error', error) return error }) } function App() { const [response, setResponse] = useState() const [isLoading, setIsLoading] = useState(false) async function getResponse() { setIsLoading(true) const getResponseData = await get() setResponse((existing) => ({ ...existing, get: getResponseData })) setIsLoading(false) } async function postResponse() { setIsLoading(true) const postResponseData = await post() setResponse((existing) => ({ ...existing, post: postResponseData })) setIsLoading(false) } function refresh() { getResponse() postResponse() } useEffect(() => { refresh() }, []) return (
    {isLoading && Loading...}
    {JSON.stringify(response, null, 2)}
    ) } export default withAuthenticator(App) ```
  8. run the Next.js development server with yarn next and authenticate

    image

What is the status code you're receiving on the failed POST call?

RoniqueRicketts commented 3 years ago

@josefaidt I tried your above suggestion line by line and it didn't work I am still getting a cors error. I've even names the files the same way you've named yours. I am getting the error Cors Error - Cross-Origin Resource Sharing error: MissingAllowOriginHeader. This said that x-cache Error from cloudfront and x-amzn-errortype: AccessDeniedException. When I check cloudfront I see a policy that says

Headers - Include the following headers
origin
access-control-request-headers
access-control-request-method

Should that origin be Access-Control-Allow-Origin

andrecasal commented 3 years ago

I replicated your steps to the letter but the request still failed.

I think the only difference between your project and mine is that I'm adding Amplify.configuration(config) manually because of this bug:

import config from 'aws-exports'
import manualConfig from 'aws-manual-config'
const extendedConfig = {
    Auth: {...config},
    API: { ...manualConfig}
}
Amplify.configure(extendedConfig)

I'll run amplify pull --appId <appid> --envName production on a clean clone (without the amplify folder or aws-exports.js) to see if the request succeeds.

josefaidt commented 3 years ago

@andrecasal what is the aws-manual-config import? We should be able to import the exports directly and configure. Can you paste the contents of your aws-exports.js file, omitting sensitive information?

// src/aws-exports.js
const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_cognito_identity_pool_id": "us-east-1:7ac69283-cd4a-4b30-a5ae-d333d35204d5",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_uHLbyAykk",
    "aws_user_pools_web_client_id": "703tihquc418thtstp62d4l9t9",
    "oauth": {},
    "aws_cloud_logic_custom": [
        {
            "name": "api8019two",
            "endpoint": "https://xxxxx.execute-api.us-east-1.amazonaws.com/dev",
            "region": "us-east-1"
        }
    ]
};

export default awsmobile;

@RoniqueRicketts how are you calling the API? What is the status code you're receiving on the failed call?

andrecasal commented 3 years ago

I just cloned the project and ran amplify pull --appId <appid> --envName production.

The aws-exports.js:

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = {
    "aws_project_region": "us-east-2",
    "aws_cognito_identity_pool_id": "us-east-2:086e60d4-4f55-4444-94bc-41c22",
    "aws_cognito_region": "us-east-2",
    "aws_user_pools_id": "us-east-2_uOLq7",
    "aws_user_pools_web_client_id": "46gbgpvr9nlnc8aie4h",
    "oauth": {},
    "aws_cloud_logic_custom": [
        {
            "name": "stripeAPI",
            "endpoint": "https://xxxxx.execute-api.us-east-2.amazonaws.com/production",
            "region": "us-east-2"
        }
    ]
};

export default awsmobile;

My previous aws-manual-config.js file:

const manualconfig = {
    endpoints: [
        {
            name: 'stripeAPI',
            endpoint: 'https://xxxxxx.execute-api.us-east-2.amazonaws.com/production'
        },
    ]
}

export default manualconfig
josefaidt commented 3 years ago

Thanks @andrecasal for the information, are you able to import just the generated aws-exports.js file and configure Amplify?

import { Amplify } from 'aws-amplify'
import config from '../aws-exports.js'

Amplify.configure(config)
RoniqueRicketts commented 3 years ago

@josefaidt That's the thing there is not status code. it just says Cors error cors error This is what it looks like. exception There is also this exception on the response.

andrecasal commented 3 years ago

Thanks @andrecasal for the information, are you able to import just the generated aws-exports.js file and configure Amplify?

import { Amplify } from 'aws-amplify'
import config from '../aws-exports.js'

Amplify.configure(config)

Yeah, I cloned my project, deleted the amplify folder and the aws-exports.js file, ran amplify pull --appId <appid> --envName production and change the code to:

import config from 'aws-exports'
Amplify.configure(config)
andrecasal commented 3 years ago

I think @RoniqueRicketts and me have the exact same problem.

andrecasal commented 3 years ago

Cloning my project and retrying everything from amplify init on a new environment

josefaidt commented 3 years ago

@RoniqueRicketts and @andrecasal do y'all have Firefox installed and can look at the request there? Their dev tools will show the status

andrecasal commented 3 years ago

@RoniqueRicketts and @andrecasal do y'all have Firefox installed and can look at the request there? Their dev tools will show the status

I'm on it.

RoniqueRicketts commented 3 years ago

Error 403

andrecasal commented 3 years ago

Firefox still doesn't show the status for me.

Screenshot 2021-08-25 at 16 25 11
andrecasal commented 3 years ago

Oh, it shows up here (403 Forbidden):

Screenshot 2021-08-25 at 16 25 57
josefaidt commented 3 years ago

Ah thank you @andrecasal and @RoniqueRicketts ! This error appears to be common in a failed call, for instance if we make a POST call to a GET only route.

What dependencies are installed for the frontend? I'm installing the following:

yarn add next react react-dom classnames @aws-amplify/ui-react aws-amplify
andrecasal commented 3 years ago

Here's my package.json:

{
    "name": "software-engineering-boss",
    "version": "1.0.0",
    "private": true,
    "description": "Software Engineering Boss",
    "author": "André Casal",
    "keywords": [
        "gatsby"
    ],
    "scripts": {
        "start": "start-server-and-test develop http://localhost:8000 tests",
        "tests": "npx cypress open",
        "develop": "gatsby develop",
        "build": "gatsby build",
        "serve": "gatsby serve",
        "clean": "gatsby clean",
        "storybook": "start-storybook -p 6006",
        "build-storybook": "build-storybook",
        "content": "cd content && sanity start"
    },
    "dependencies": {
        "@aws-amplify/ui-react": "^1.2.8",
        "@reduxjs/toolkit": "^1.6.1",
        "@stripe/stripe-js": "^1.17.1",
        "aws-amplify": "^4.2.2",
        "axios": "^0.21.1",
        "babel-plugin-styled-components": "^1.13.2",
        "dotenv": "^10.0.0",
        "gatsby": "^3.10.1",
        "gatsby-plugin-image": "^1.10.1",
        "gatsby-plugin-manifest": "^3.10.0",
        "gatsby-plugin-sharp": "^3.10.2",
        "gatsby-plugin-sitemap": "^4.6.0",
        "gatsby-plugin-styled-components": "^4.11.0",
        "gatsby-source-filesystem": "^3.10.0",
        "gatsby-source-sanity": "^7.0.7",
        "gatsby-transformer-sharp": "^3.10.0",
        "normalize.css": "^8.0.1",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-icons": "^4.2.0",
        "react-redux": "^7.2.4",
        "styled-components": "^5.3.0"
    },
    "devDependencies": {
        "@babel/core": "^7.15.0",
        "@storybook/addon-actions": "^6.3.6",
        "@storybook/addon-essentials": "^6.3.6",
        "@storybook/addon-links": "^6.3.6",
        "@storybook/builder-webpack5": "^6.3.6",
        "@storybook/manager-webpack5": "^6.3.6",
        "@storybook/react": "^6.3.6",
        "@testing-library/cypress": "^8.0.0",
        "aws-sdk-mock": "^5.2.2",
        "babel-loader": "^8.2.2",
        "cypress": "^8.3.0",
        "cypress-cucumber-preprocessor": "^4.2.0",
        "cypress-hmr-restarter": "^2.0.2",
        "gatsby-plugin-root-import": "^2.0.7",
        "start-server-and-test": "^1.13.1"
    },
    "cypress-cucumber-preprocessor": {
        "nonGlobalStepDefinitions": true
    }
}
josefaidt commented 3 years ago

@andrecasal do you have this project in a public repository? I'll see if I can recreate with Gatsby instead of Next.js

andrecasal commented 3 years ago

It's private but I can give you access.

andrecasal commented 3 years ago

I can't find you on GitHub 🤔

Screenshot 2021-08-25 at 17 21 47
josefaidt commented 3 years ago

@andrecasal try searching without the leading @

josefaidt commented 3 years ago

I've pushed my Next.js example to its own repo https://github.com/josefaidt/8019

andrecasal commented 3 years ago

@andrecasal try searching without the leading @

I've invited you now 👍

andrecasal commented 3 years ago

I'm trying to rebuild the whole backend from scratch on a clone project. I forgot to npm install stripe on the Lambda function for this clone. It's funny that the exact same CORS error shows up. The only difference is the x-amzn-errortype header.

Screenshot 2021-08-25 at 17 50 54 Screenshot 2021-08-25 at 17 51 04

This leads me to suspect the CORS issue is just a symptom of the problem, but not the actual problem.

josefaidt commented 3 years ago

Hey @andrecasal and @RoniqueRicketts from our discussions today we've noted a few things:

With this information I will label this issue with documentation to update with notes regarding CORS-related errors and how to work through them. I'll also meet with some folks from the team to see if we can improve on the ambiguous CORS errors that are returned from the API.

RoniqueRicketts commented 3 years ago

My request was getting blocked with a 403 Error code. My requests were getting block at the api gateway level and I was unable to hit my lambda functions associated with the API. The reason behind this failure was that I had added users groups to my Cognito Userpool before running amplify add api . When user groups are added user roles are also added but no policies are associated with said user role. My suggestion would be to update any user Role policy with the permission to access the api-gateway service when we run amplify add api to a project that already has cognito userpools added.

josefaidt commented 3 years ago

There's an open issue in amplify-js for reading response body on 4xx responses from API Gateway, seems relevant to improving the messaging to some degree https://github.com/aws-amplify/amplify-js/issues/8806

andrecasal commented 3 years ago

For lack of a better option, I resolved this issue by redeploying my backend infrastructure from scratch.

Here's what I did:

  1. Made a backup copy of all my files
  2. Deleted the amplify folder and the aws-exports.js file
  3. Deleted the production environment from Amplify's Admin UI (hosting, auth, API, and functions are gone)
  4. Create a backend environment using AWS Amplify Console (the default environment is called staging and you can't change that)
  5. Ran amplify pull --appId xxxxxxxx --envName production on the root of my repo to get access to that backend from the CLI
  6. Ran amplify env add production to add a backend environment called production
  7. Ran amplify env remove staging to remove the default backend environment staging (unfortunately one has to do this gymnastic because you can't change the default environment name)
  8. Ran amplify push to save changes to the cloud
  9. On Amplify's Admin UI, added auth (I can't do this using the CLI because it forces a username field on my frontend)
  10. Ran amplify add api allowing access only to authorized users
  11. Ran amplify push to save changes

Now I can only hit my API from logged-in users ✅

RoniqueRicketts commented 3 years ago

Just a side note for those who may have created Auth with groups before creating the API look out for your Auth Group Roles to be without a policy. If you're unable to hit you API successfully you may have to manually Create a policy that grants access to your API. Ps. Please remember AWS's limited access approach first even though those full access policies looks tempting custom policies make your application a little more secure. Hopefully in the next Amplify release the team will be able to update those policies according when a user adds Amplify Auth before Amplify API. @josefaidt

jasonhargrove commented 3 years ago

thanks @RoniqueRicketts, I followed your trail and solved my CORS issue, which suddenly appeared after adding groups and cognito in the identity pool

solved this in the IAM ui

jasonhargrove commented 3 years ago

not sure but did not seem to matter which order I added auth or api as reported, so I dug a little further

tldr; after you add a group, you can use CLI to update your API, and attach the policy for that group

just now solved this with the cli, which is probably the intended flow

pepso commented 2 years ago

@josefaidt I strongly suggest this is not a documentation issue, but real technical problem with amplify-cli. Do I create a new issue, or can you reopen this and triage further as per my below details?

  1. I have an API originally created with amplify-cli version ~4.20 with 10 or so paths all working fine and dandy
  2. I was able to upgrade amplify-cli up to 4.52.0 version with manual workaround of parameters.json file clean up, and also getting the auth/unAuth roles recreated as per 4.50.2 minor version upgrade (which fixes api migration to new style of configuring the api gateway)
  3. I created a new api path, a standard lambda as per my project (same "template" as other end points) and I got CORS all over. APIGateway does not invoke the lambda function associated with the newly created path
  4. I decided to create a full "new" lambda example as per the amplify-cli walkthrough like this: image
  5. Deployment all ok, but when I try to GET the end point (from remote server/localhost, or from deployed cloud stack [dev]) I get into CORS trouble.
  6. OPTIONS returns 200, but GET fails: image

Please keep in mind every other API path in the same API Gateway end point continue to work, and be invoked as expected (created and deployed pre-4.50 amplify-cli). This impacts only the new paths created since 4.50.2 upgrade (which was supposed to fix the API migration issues).

I don't believe this to be documentation only issue, and it got to involve at least newly created out of box api path into an existing api + lambda walkthroughs update so the codegen works as expected.

Please advise what needs to be done to fix the disconnect between amplicy-cli created templates to working API path to Lambda invokes without CORS.

pepso commented 2 years ago

I fixed my issue and identified a breaking change in the way how amplify handles api calls/paths between versions:

Background: In my web-app, every API call to my endpoints contain couple of variables in the body of the call (where I transfer some metrics about the user experience). In my backend I parse them with middleware using app.use(metricParsers()).

I found out that there is a change API paths created pre-4.50.2, GET calls with "body" go through API Gatway API paths created post-4.50.2, GET calls fail as CORS error if body is defined as part of the paylod

Basically I conclude that API Gateway configuration have become more strict with API updates in past couple of months.

RoniqueRicketts commented 2 years ago

@pepso as per the information sent by @jasonhargrove above you'll have to update the API to the groups you make. I surely believe the documentation should update on every update with beginner friendly content. That could minimize a lot of issue that I'm seeing on here. Right now there is also an issue with the API getting custom_headers but the documentation suggests how to send them but the information is incorrect as it doesn't match the actual reaction of the API on API Gateway.

pepso commented 2 years ago

@RoniqueRicketts thanks for the offer to help. I haven't created groups to my cognito, so it would be a surprise I would require an update to any groups.

My problem was solved literally by removing body:{} from the API call options. This is a call which works against GET paths created with earlier amplify-cli version:

const APIName = 'apiname';
const URL = '/endpoint';
const options = { 
    headers: { "Content-Type": "application/json" }, 
    body: {},
    response: true 
};
const response = await API.get(APIName, URL, options);

And this is an API call which works post-4.50.2 amplify-cli created API paths:

const APIName = 'apiname';
const URL = '/endpoint';
const options = { 
    headers: { "Content-Type": "application/json" }, 
    response: true 
};
const response = await API.get(APIName, URL, options);

Using body as part of the GET call obviously is not according to the HTTP definition, but I just happend to use it to move some telemetry data from the app to the backend... Headers themselves have a limit (4-8Kb) depending on webserver of choice and its config) how much data you can transfer and for certain use cases the body is better place to transfer big telemetry payloads.

josefaidt commented 2 years ago

Hey @pepso 👋 are you sending the CORS headers from your Lambda? Are you seeing without adding those headers that the GET call succeeds with restriction enabled?

pepso commented 2 years ago

@josefaidt yes, I'm sending the CORS headers as per usual.

If the body:{} is part of the payload, call never reaches lambda / lambda is not invoked by API gateway.

josefaidt commented 2 years ago

@pepso do you have your code in a public repository? I was not experiencing this with GET calls, shown with my example from https://github.com/aws-amplify/amplify-cli/issues/8019#issuecomment-905513096. Can you share what your Lambda code looks like?

pepso commented 2 years ago

@josefaidt I have remove the test end point which I used to narrow down the problem (from my private repo), but it was the box standard template generated by amplify-cli:

image

The example you mention in your comment differs significantly from the setup I have. In my setup amplify api add was done on amplify-cli version ~4.20 and the discussed amplify api update to add new path was with aplify-cli version 4.50.2

The lambda code does not get invoked as the payload is not going through the API Gateway.

If you want to replicate the problem as I have it, you probably need to start with older cli version by creating an API and migrateing it into newer versions step at a time.

This is my upgrade path "story" if you want to replicate it: I created my API originally on ~4.20 version. I was stuck on 4.29.2 for a long time due to change to init --force flag issue. When that was fixed on the CLI and I eventually got around to use the newly introduced flag, I upgraded to the 4.42 version. With this version I could not deploy any new APIs because CloudFormation updates were failing to auth/unAuth variable missing message. Later on I learned I need to manually remove auth/unAuth variables from parameters.json file as a workaround. Then, 4.50.2 actually fixed the auth/unAuth roles for my API Gateway. This is where I am at right now. For new api path created with current version, GET with body:{} fails to CORS with invalid signature without triggering the underlying lambda. GET with body:{} against the previously created api paths continue to work.

My current workaround is not to send body as part of GET payload to avoid this issue. I guess I stick with this until I have energy and time to try to upgrade 5.X onward.

@josefaidt a question about upgrade path to 5.x in mind... https://docs.amplify.aws/cli/migration/lambda-layers-update/

Can you confirm lambda layer one-way upgrade process is triggered also when deploying using amplify CD/init and I do NOT need to amplify push command from local dev box to cloud environments (dev/integration/production)?

josefaidt commented 2 years ago

Hey y'all :wave: this issue should now be fixed per https://github.com/aws-amplify/amplify-cli/pull/9158. Closing issue, if you are still experiencing issues related to CORS with REST API's please create a new bug report or reply back to this thread and we can re-open to investigate further 🙂

ranyakhemiri commented 1 year ago

I had the same error and checked the Lambda logs, turns out the lambda was running out of memory. So I increased the memory and timeout and it solved the issue! Also enabling CORS through API Gateway console didn't solve the issue for some reason, but enabling CORS in the lambda code helped solve the issue :

    return {
        statusCode: 200,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Headers": "*"
      }, 
        body: ... ,
    };

Hope this helps anybody struggling with the same issue!

salmandjing commented 9 months ago

I had the same error and checked the Lambda logs, turns out the lambda was running out of memory. So I increased the memory and timeout and it solved the issue! Also enabling CORS through API Gateway console didn't solve the issue for some reason, but enabling CORS in the lambda code helped solve the issue :

    return {
        statusCode: 200,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Headers": "*"
      }, 
        body: ... ,
    };

Hope this helps anybody struggling with the same issue!

Thank you so much. Took forever to find this solution.