sst / guide

Repo for guide.sst.dev
https://guide.sst.dev
MIT License
3.68k stars 445 forks source link

Comments: Test the APIs #112

Closed jayair closed 6 years ago

jayair commented 7 years ago

Link to chapter - http://serverless-stack.com/chapters/test-the-apis.html

jcowley commented 7 years ago

Okay, for me the signature issue was caused by having a trailing slash on the invoke-url, e.g.:

...
--invoke-url='https://ly55wbovq4.execute-api.us-east-1.amazonaws.com/prod/'
--path-template='/notes' \
...

The invoke url and path are combined by aws-api-gateway-cli-test and resulted in a double slash in the URL, which would (I guess) result in a different signature than the one AWS would expect for the request.

Removing the slash after prod fixed it for me:

...
--invoke-url='https://ly55wbovq4.execute-api.us-east-1.amazonaws.com/prod'
--path-template='/notes' \
...

So maybe double check your invoke-url and path-template.

jayair commented 7 years ago

@bradodarb Just tried your repo. It worked fine for me.

screen shot 2017-07-25 at 1 32 31 pm

This error is because of the code but all the auth stuff worked okay.

screen shot 2017-07-25 at 1 36 33 pm

Can I get the name of the IAM Policy in your Identity Pool? Or if you could post a screenshot like so.

screen shot 2017-07-22 at 3 14 54 pm
jayair commented 7 years ago

@bradodarb One other thing to try is the Policy Simulator like @neowulf33 suggested - https://policysim.aws.amazon.com/home/index.jsp?#roles

Pick your IAM Role, Select a Service (API Gateway), Select an action (Invoke), Add the ARN and Run Simulation.

screen shot 2017-07-25 at 2 08 55 pm

jayair commented 7 years ago

@jugglingcats @limifont You guys can try the above as well and let me know how it goes.

jayair commented 7 years ago

@deepseafishing From looking at your serverless.yml it looks like the iamRoleStatements is on the save level of indentation as the provider. It shouldn't be so, compare it against the one in the repo to make sure it looks okay.

jayair commented 7 years ago

@mikhaelbendavid You'd need to make sure the user is created like in this chapter - http://serverless-stack.com/chapters/create-a-cognito-test-user.html

You can also go into the User Pool > Users and groups > and check if the user is enabled and confirmed like so.

screen shot 2017-07-25 at 2 19 01 pm
jayair commented 7 years ago

@jcowley Thanks for reporting back!

algalvez commented 7 years ago

for those having problems with windows cmd, this worked for me:

apig-test --username admin@example.com --password Passw0rd! --user-pool-id YOUR_COGNITO_USER_POOL_ID --app-client-id YOUR_COGNITO_APP_CLIENT_ID --cognito-region YOUR_COGNITO_REGION --identity-pool-id YOUR_IDENTITY_POOL_ID --invoke-url YOUR_API_GATEWAY_URL --api-gateway-region YOUR_API_GATEWAY_REGION --path-template notes --method POST --body "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}"

jayair commented 7 years ago

@algalvez Thanks for posting this. I'm sure it'll help!

deepseafishing commented 7 years ago

@jayair Thank you so much. I've been trying to figure this out several hours. You saved my life, thanks! In general, is there a linter or a clever way to figure out the mistakes I made in yml file?

jayair commented 7 years ago

@deepseafishing That's a good point. I haven't looked into it but it shouldn't be hard to do as long as there is a spec.

bradodarb commented 7 years ago

@jayair thank you for awesome support. I know once I get past my learning curve I can count on the eco-system and that's pretty great.

Not out of the woods but good to confirm whatever is buggered is between me and the aws console.

I must fundamentally misunderstand how roles operate. You've previously verified my inline policy checks out for that role and I've attached the ApiGatewateInvokeFullAccess as well yet I am denied in the policy simulator...

image

I've got some manuals to read I reckon.

EDIT: I didn't input the resource url..... durr. I'll try that later and update.

jugglingcats commented 7 years ago

Hi @jayair, I carefully followed all the steps again from scratch but this time in the us-east-1 region (I was in eu-west-1) and unfortunately get the same error. Below is my policy simulation output - looks ok.

image

I notice there are no Authorizers configured in the API Gateway. Is that correct?

For completeness, here is my console output (I modified all the ids):

$ apig-test \
> --username='admin@example.com' \
> --password='Passw0rd!' \
> --user-pool-id='us-east-1_Xvz1pDxGp' \
> --app-client-id='190ahtjqcvde2hcm3drivdch64' \
> --cognito-region='us-east-1' \
> --identity-pool-id='us-east-1:9c221ab2-ec83-4e4f-9e41-b25ca12c5a02' \
> --invoke-url='https://fcvjf9nzlq.execute-api.us-east-1.amazonaws.com/prod' \
> --api-gateway-region='us-east-1' \
> --path-template='/notes' \
> --method='POST' \
> --body='{"content":"hello world","attachment":"hello.jpg"}'
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
  statusText: 'Forbidden',
  data: { message: 'Forbidden' } }
neowulf commented 7 years ago

The plot thickens.

The following error indicates the policy attached to the auth role defined in Federated Pool needs to be updated with the api gateway id

Authenticating with User Pool
Getting temporary credentials
Invalid login token. Couldn't verify signed token.

This is the error that we are all seeing.

Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
  statusText: 'Forbidden',
  data: { message: 'Forbidden' } }

When testing the lambda function using the serverless invocation, the result is good.

{ statusCode: 200,
  headers: 
   { 'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Credentials': true },
  body: '{"userId":"USER-SUB-1234","noteId":"3c726b10-7185-11e7-b72a-71e7c1934e33","content":"hello world","attachment":"hello.jpg","createdAt":1501020271681}' }

When testing the lambda function directly by going to Lambda > Functions > "function name" > Test and providing the following payload to test against:

{
  "body": "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}",
  "requestContext": {
    "identity": {
      "cognitoIdentityId": "USER-SUB-1234"
    }
  }
}

I get the following error:

{
  "errorMessage": "Cannot find module 'babel-runtime/regenerator'",
  "errorType": "Error",
  "stackTrace": [
    "Object.<anonymous> (/var/task/lambda_note_create.js:87:18)",
    "__webpack_require__ (/var/task/lambda_note_create.js:20:30)",
    "Object.<anonymous> (/var/task/lambda_note_create.js:187:20)",
    "__webpack_require__ (/var/task/lambda_note_create.js:20:30)",
    "Object.defineProperty.value (/var/task/lambda_note_create.js:63:18)",
    "Object.<anonymous> (/var/task/lambda_note_create.js:66:10)"
  ]
}

I see the same error when testing the API gateway as well via the API gateway console.

Question: Does serverless webpack invoke invoke the remote lambda function in the cloud or invoke the local function which accesses the remote dynamodb?

Update

Cloned and ran the lambda function created by https://github.com/AnomalyInnovations/serverless-es7

Looks like something wonky is going on in my deployment. Will have to investigate.

Are there any pointers in helping resolve the babel-runtime/regenerator issue?

Thanks!

jayair commented 7 years ago

@neowulf33 I'm not exactly sure what's causing the babel issue. But make sure you are using Serverless 1.17.0 for now (as per this - https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-317217381).

Edit:

Yeah serverless webpack invoke runs the function locally while accessing the remote resources.

jayair commented 7 years ago

@jugglingcats Can I try your repo as well? Just to make sure the issue isn't in the code.

jayair commented 7 years ago

@bradodarb Thanks for the update.

I'd really like to figure out what this issue is. It's probably something in the setup that we need to make clear for everybody.

bradodarb commented 7 years ago

@jayair

I used the following arn and seems to auth where it was not with '*' image

What is troubling it seems to auth no matter the API Gateway Id I use....?

arn:aws:execute-api:us-east-1::ps8mmgaj2c/

vs

arn:aws:execute-api:us-east-1::super-legit-id/

both return 'allowed'

Is that expected behavior?

jayair commented 7 years ago

@bradodarb No it should not...

On the left sidebar if you click on the role, it'll show you the policy. Can you copy and paste that here?

bradodarb commented 7 years ago

@jayair , this is certainly an issue with my understanding of AWS rather than a serverless problem.
If nothing pops out at you I'll try recreating demo from scratch again.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::m4-user-assets/${cognito-identity.amazonaws.com:sub}*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "execute-api:Invoke"
            ],
            "Resource": [
                "arn:aws:execute-api:us-east-1:*:ps8mmgaj2c/*"
            ]
        }
    ]
}
bradodarb commented 7 years ago

Another follow-up, @jayair :

Ok..... made some progress. Turns out I was in fact able to follow directions(for the most part).... maybe.

I changed my test command-

From:

apig-test \
--username='admin@example.com' \
--password='Passw0rd!' \
--user-pool-id='YOUR_COGNITO_USER_POOL_ID' \
--app-client-id='YOUR_COGNITO_APP_CLIENT_ID' \
--cognito-region='YOUR_COGNITO_REGION' \
--identity-pool-id='YOUR_IDENTITY_POOL_ID' \
--invoke-url='YOUR_API_GATEWAY_URL' \
--api-gateway-region='YOUR_API_GATEWAY_REGION' \
--path-template='/notes' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'

To:

--username='admin@example.com' \
--password='Passw0rd!' \
--user-pool-id='YOUR_COGNITO_USER_POOL_ID' \
--app-client-id='YOUR_COGNITO_APP_CLIENT_ID' \
--cognito-region='YOUR_COGNITO_REGION' \
--identity-pool-id='YOUR_IDENTITY_POOL_ID' \
--invoke-url='YOUR_API_GATEWAY_URL' \
--api-gateway-region='YOUR_API_GATEWAY_REGION' \
--path-template='' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'

In other words I set the --path-template var to an empty string (otherwise complained about required parameter if completely omitted) and put the entire invoke-url from the console into the --invoke-url parameter(in my case : --invoke-url='https://ps8mmgaj2c.execute-api.us-east-1.amazonaws.com/dev/mail')

Now I actually get events in my Cloudwatch logs!!

I wonder if the test tool has been updated since example created?

Unfortunately I'm still not getting a good response but I am getting some good errors:

(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Method request path:
{}
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Method request query string:
{}
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Method request headers: {X-AMZ-Date=20170726T055040Z, Accept=application/json, CloudFront-Viewer-Country=US, CloudFront-Forwarded-Proto=https, CloudFront-Is-Tablet-Viewer=false, CloudFront-Is-Mobile-Viewer=false, User-Agent=axios/0.16.2, X-Forwarded-Proto=https, CloudFront-Is-SmartTV-Viewer=false, Host=ps8mmgaj2c.execute-api.us-east-1.amazonaws.com, x-amz-security-token=AgoGb3JpZ2luEJL//////////wEaCXVzLWVhc3QtMSKAAnRMtse6Y20itJg3up+Qzh5fGTus0ZNTbhLrh0ctiwtksJm39lPquCHM44somB5HtkSd8plWTInO9fk0FQi4woPOqVP+TZxX8qLHY0fZVx79azQ7zNw2Vdq8jn4Xu/uLRmjmpjwJUUtaHT9qHfkF2F8vLDmgLk/fQECsQWojxJo23Gs8o+cZP/aCTStmo+BYheFSr0fLTxnxTboBABlnoykhmsz9b+pk/84TuO1iDdwHgwvfBFNAQkpTlx6F7uuXRAhUEogDjODQubYX1TloxKzWZr6wSJa2nsraXXKOOds++WOl+bjBwHz3nNHcNnNPYppFTOOra7RxlWFvJeVcJ6QqpgUIJxAAGgwzOTg2OTE3NzcyMDkiDLFOebiqeaKgn14hbiqDBWw7fvPuigt/cZ++8UaIbTEVdU8XGD3CYsqCj2UtWu0Z6MwBzsOmWlv4QPnpUXp5H3D+OPglNeNuxdXl12tKLVrDX6Siy+HJsLMOegOAuoODMzhJr3LeCTa/Io2zr3H07+t0FM0meS9WX+EYI8WTkAXiESKInwaElK3CANlopQ6MY4sQPd+lAIVqWgwOlLh712W5mv8hfqlMk76zRZYKvwb [TRUNCATED]
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Method request body before transformations:
{
    "content": "hello world",
    "attachment": "hello.jpg"
}
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Endpoint request URI: https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:398691777209:function:m4-user-mail-api-dev-create/invocations
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Endpoint request headers: {x-amzn-lambda-integration-tag=5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc, Authorization=****************************************************************************************************************************************************************************************************************************************************************************************************************************************83480f, X-Amz-Date=20170726T055039Z, x-amzn-apigateway-api-id=ps8mmgaj2c, X-Amz-Source-Arn=arn:aws:execute-api:us-east-1:398691777209:ps8mmgaj2c/dev/POST/mail, Accept=application/json, User-Agent=AmazonAPIGateway_ps8mmgaj2c, X-Amz-Security-Token=FQoDYXdzECYaDG7ov3zM8ORn9htN/CK3A0rTX5h6kB+EClGcy/+FlK8Xtwp5TEkvZ1yBYm7qtRXSrZwUucOP76zsEVotHLPEf5PfV8AdUg7zE+u7YgjCUGuSrf6aBjXwEdYQgpMZw7ePwTLTAjA+g/dCQtp2q59jEm48Z9v2CGkMmYn09pIYEeJf2bbkfVLr/0Hjmf9AWD8uP3m+crXYlmy8oVMTtX0jWa/T8OL8yZx8QTzp8h0izpeFXz70pXtMPIo9/ds2cU4DGvgGhd5dCO0bU/pUToerR4C37zx8G6FLXsK8CkmPiGOjpSI+EGo6kz4h1ISZYvjO8YqzlvXrv [TRUNCATED]
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Endpoint request body after transformations: {"resource":"/mail","path":"/mail","httpMethod":"POST","headers":{"Accept":"application/json","CloudFront-Forwarded-Proto":"https","CloudFront-Is-Desktop-Viewer":"true","CloudFront-Is-Mobile-Viewer":"false","CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer":"false","CloudFront-Viewer-Country":"US","Content-Type":"application/json","Host":"ps8mmgaj2c.execute-api.us-east-1.amazonaws.com","User-Agent":"axios/0.16.2","Via":"1.1 86f2bbfea57d6217ce2d279b84ca3743.cloudfront.net (CloudFront)","X-Amz-Cf-Id":"P8nmAi87EEbhos39DdWAGfKI3u660Y5HxTdL6JGs79Qlil6ZWUjXTw==","X-AMZ-Date":"20170726T055040Z","x-amz-security-token":"AgoGb3JpZ2luEJL//////////wEaCXVzLWVhc3QtMSKAAnRMtse6Y20itJg3up+Qzh5fGTus0ZNTbhLrh0ctiwtksJm39lPquCHM44somB5HtkSd8plWTInO9fk0FQi4woPOqVP+TZxX8qLHY0fZVx79azQ7zNw2Vdq8jn4Xu/uLRmjmpjwJUUtaHT9qHfkF2F8vLDmgLk/fQECsQWojxJo23Gs8o+cZP/aCTStmo+BYheFSr0fLTxnxTboBABlnoykhmsz9b+pk/84TuO1iDdwHgwvfBFNAQkpTlx6F7uuXRAhUEogDjODQubYX1TloxKzWZr6wSJa2nsraXXKOOd [TRUNCATED]
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Endpoint response body before transformations:
{
    "errorMessage": "Cannot find module 'babel-runtime/regenerator'",
    "errorType": "Error",
    "stackTrace": [
        "Function.Module._load (module.js:417:25)",
        "Module.require (module.js:497:17)",
        "require (internal/module.js:20:19)",
        "Object.<anonymous> (/var/task/create.js:70:18)",
        "__webpack_require__ (/var/task/create.js:20:30)",
        "Object.<anonymous> (/var/task/create.js:171:20)",
        "__webpack_require__ (/var/task/create.js:20:30)",
        "/var/task/create.js:63:18",
        "Object.<anonymous> (/var/task/create.js:66:10)"
    ]
}
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Endpoint response headers: {x-amzn-Remapped-Content-Length=0, x-amzn-RequestId=5a92e8f2-71c6-11e7-8456-71a6d7356212, Connection=keep-alive, Content-Length=492, X-Amz-Function-Error=Unhandled, Date=Wed, 26 Jul 2017 05:50:39 GMT, X-Amzn-Trace-Id=root=1-59782daf-0b908232481c89670257abc5;sampled=0, Content-Type=application/json}
(5a7bdeb9-71c6-11e7-9822-09ff9d23e4cc) Execution failed due to configuration error: Malformed Lambda proxy response

Seems like a possible deployment issue now?

bradodarb commented 7 years ago

Some cursory googling on that last line led me to believe the response object from the create function should be stringified so I changed the callback to this:


        callback(null, success(JSON.stringify(params.Item), 201));

But no dice.... same error shows up in logs.

sidthe commented 7 years ago

@bradodarb I am having something similar in my logs, have you found a solution for that?

This is from CloudWatch

Unable to import module 'create': Error
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/task/create.js:76:18)
at __webpack_require__ (/var/task/create.js:20:30)
at Object.<anonymous> (/var/task/create.js:167:20)
at __webpack_require__ (/var/task/create.js:20:30)
at /var/task/create.js:63:18
at Object.<anonymous> (/var/task/create.js:66:10)

And this is directly when I try to test the create method in the API Gateway

Wed Jul 26 10:56:00 UTC 2017 : Received response. Integration latency: 75 ms
Wed Jul 26 10:56:00 UTC 2017 : Endpoint response body before transformations: 
{"errorMessage":"Cannot find module 'babel-runtime/regenerator'","errorType":"Error","stackTrace
["Object.<anonymous> (/var/task/create.js:76:18)","__webpack_require__
(/var/task/create.js:20:30)","Object.<anonymous> 
(/var/task/create.js:167:20)","__webpack_require__ 
(/var/task/create.js:20:30)","/var/task/create.js:63:18",
"Object.<anonymous> (/var/task/create.js:66:10)"]}
sidthe commented 7 years ago

Found this https://github.com/serverless/serverless/issues/3918

bradodarb commented 7 years ago

@sidthe - I stumbled across that as well. I have no .npmrc in my project and I checked my global .npmrc and long=true was not present.

jayair commented 7 years ago

@sidthe Your error looks like the one people were seeing above - https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-317217381

Just make sure you are running Serverless 1.17.0 for now.

@bradodarb For your case as well. It's a bit weird that it's not packaging the dependency babel-runtime. Make sure you are on 1.17.0 by running serverless -v.

sidthe commented 7 years ago

@jayair I am on 1.17.0

I just got rid of the error by including into the serverless.yml the following

package:
  excludeDevDependencies: false

I am now getting a 500 but at least no dependency issue in the log

sidthe commented 7 years ago

@jayair my bad, I was indeed on 1.18.0, looks like accidentally updated. Now the package dependency is gone, even without the above fix. Still getting a status:false, but probably not the same issue

jayair commented 7 years ago

@sidthe That makes sense. You shouldn't need the excludeDevDependencies flag on 1.17.0. For the status: false follow this - http://serverless-stack.com/chapters/test-the-apis.html#common-issues

sidthe commented 7 years ago

@jayair thanks a lot. One more question related to the chapter. My API test returns 500. Interestingly enough however, when I run the test from within Lambda, they execute succesfully and I get the data back. Any reason the function test would pass in Lambda but would return a server error in API Gateway?

I added logging to the handlers, but nothing shows up in the logs.

jayair commented 7 years ago

@sidthe When you run the test from Lambda, do you mean in your local or through the AWS Console?

sidthe commented 7 years ago

@jayair through the aws console

neowulf commented 7 years ago

I did indeed need to downgrade my serverless version as @jayair mentioned:

$ npm uninstall -g serverless
$ npm install -g serverless@1.17.0

To enable cloudwatch logs for api gateway:

https://kennbrodhagen.net/2016/07/23/how-to-enable-logging-for-api-gateway/

After following the steps in the previous article, I have staged the api gateway. I am able to look at logs coming in from api gateway and lambda functions. These two services can be tested independently.

Thanks to @jcowley 's comment - I now get the proper http response when invoking the staged api gateway url (notice my --invoke-url):

$ apig-test \
> --username='admin@example.com' \
> --password='Passw0rd!' \
> --user-pool-id='xxxx' \
> --app-client-id='xxxx' \
> --cognito-region='us-west-2' \
> --identity-pool-id='xxxx' \
> --invoke-url='https://xxxx.execute-api.us-west-2.amazonaws.com/stage' \
> --api-gateway-region='us-west-2' \
> --path-template='/notes' \
> --method='POST' \
> --body='{"content":"hello world","attachment":"hello.jpg"}'

Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 200,
  statusText: 'OK',
  data: 
   { userId: 'us-west-2:a2e882d0-af59-472b-9ff5-6d1234527bcb',
     noteId: '8e5b69a0-7238-11e7-a677-77f7a43d3005',
     content: 'hello world',
     attachment: 'hello.jpg',
     createdAt: 1501097289018 } }

Thank you for this discussion! It was most helpful!

sidthe commented 7 years ago

ok, so my problem was different. Since my app is slightly different then the example, dynamo was expecting the range key in the call, which is not the usedid and this was triggering the failure.

bradodarb commented 7 years ago

Sure enough, rolling version back to 1.17.0 (from 1.18.0) did the trick and I'm able to successfully access my services. Thank you for your assistance, @jayair !!

The only thing a bit weird is the parameters for the testing cli.

If I have the entire URL in the --invoke-url parameter and keep --path-template empty it works.

So this accesses my APIs -

--invoke-url='https://xxxx.execute-api.us-west-2.amazonaws.com/dev/notes'
--path-template=''

If however I try:

--invoke-url='https://xxxx.execute-api.us-west-2.amazonaws.com/dev'
--path-template='/notes'

I get the 403 forbidden error.

At this point perhaps I should raise it as an issue in the test tool's repo....

Thanks again!

jugglingcats commented 7 years ago

Thanks @bradodarb I get exactly the same results as you... I have to put everything in the invoke-url.

I no longer get 403 -- and get 200 or 500 depending on whether my lambda function was successful - ie. whether my code is correct - happy days!!

jayair commented 7 years ago

@bradodarb @jugglingcats That's great to hear!

@neowulf33 Thanks to your detailed report back we've resolved this issue!

@bradodarb Also, if you could submit an issue in regards to apig-test that'll be great. I need to figure out what is going on there.

clifftai commented 7 years ago

Hi @jayair, I'm having the same problem as @limifont with the {status: 401 .... unauthorized }. I checked the policy simulator output and it seems to be fine. Any ideas? I also can't check my cloudwatch logs because it doesn't seem to be getting through api gateway, so it never reaches the lambda functions.

With further investigation, I found that I was able to call the /OPTIONS endpoint, but none of my actual lambda functions, so I feel like it has something to do with my Cognito authentication.

jayair commented 7 years ago

@clifftai Hmmm just to make sure you are using Serverless 1.17.0?

clifftai commented 7 years ago

@jayair Yep, on Serverless 1.17.0, Node 6.11.1, npm 5.0.3. If this helps, I turned off authorization in Gateway for each individual method, and that works and allows me to call each endpoint, though that seems like a fairly large security vulnerability.

jayair commented 7 years ago

@clifftai Since you checked the Policy Simulator already, just check and make sure the User Pool and Identity Pool are linked properly. The User Pool is added as a Authentication Provider in the Identity Pool like in this chapter - http://serverless-stack.com/chapters/create-a-cognito-identity-pool.html.

copperspeed commented 7 years ago

Testing api with POST request works but with GET request fails.

apig-test --username ***** --password **** --user-pool-id us-west-**** --app-client-id **** --cognito-region us-west-2 --identity-pool-id us-west-2:**** --invoke-url https://****.execute-api.us-west-2.amazonaws.com/prod --api-gateway-region us-west-2 --path-template /inventory --method GET
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
  statusText: 'Internal Server Error',
  data: { status: false } }

list.js function

import * as dynamoDbLib from './../../libs/dynamodb-lib';
import { success, failure } from './../../libs/response-lib';

export async function main(event, context, callback) {
  const params = {
    TableName: 'inventory',
  };

  try {
    const result = await dynamoDbLib.call('query', params);
    // Return the matching list of items in response body
    callback(null, success(result.Items));
  }
  catch(e) {
    console.log('list:', e);
    callback(null, failure({status: false}));
  }
};

Any ideas what it could be? I'm just trying to retrieve all items no filtering.

jayair commented 7 years ago

@copperspeed Did you try checking what the console.log('list:', e) is returning? You can have a look in the CloudWatch logs. Here is some more info on it http://serverless-stack.com/chapters/test-the-apis.html#common-issues.

RaphaelMui commented 7 years ago

@jayair My agin-test fails with a 500 Internal server error.

The Cloudwatch log shows a credential error in /home/sbx_user1060/.aws/credentials'. Am I missing something in creating the user credentials?

2017-07-31T09:13:36.802Z    888b308b-75d0-11e7-b558-b75c1d7d9052    create: { CredentialsError: Missing credentials in config
at Error (native)
at Object.fs.openSync (fs.js:641:18)
at Object.fs.readFileSync (fs.js:509:33)
at Object.readFileSync (/var/runtime/node_modules/aws-sdk/lib/util.js:97:26)
at SharedIniFile.loadFile [as ensureFileLoaded] (/var/runtime/node_modules/aws-sdk/lib/shared_ini.js:19:18)
at SharedIniFile.loadProfileNames [as getProfiles] (/var/runtime/node_modules/aws-sdk/lib/shared_ini.js:61:10)
at SharedIniFileCredentials.refresh (/var/runtime/node_modules/aws-sdk/lib/credentials/shared_ini_file_credentials.js:91:45)
at SharedIniFileCredentials.get (/var/runtime/node_modules/aws-sdk/lib/credentials.js:121:12)
at getAsyncCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:327:24)
at Config.getCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:347:9)
message: 'Missing credentials in config',
errno: -2,
code: 'CredentialsError',
syscall: 'open',
path: '/home/sbx_user1060/.aws/credentials',
time: 2017-07-31T09:13:36.798Z,
originalError: 
{ message: 'Could not load credentials from SharedIniFileCredentials',
errno: -2,
code: 'CredentialsError',
syscall: 'open',
path: '/home/sbx_user1060/.aws/credentials',
time: 2017-07-31T09:13:36.797Z,
originalError: 
{ errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/home/sbx_user1060/.aws/credentials',
message: 'ENOENT: no such file or directory, open \'/home/sbx_user1060/.aws/credentials\'' } } }
jayair commented 7 years ago

@RaphaelMui It looks like you have multiple profiles. I think somebody else had talked about this in the comments for one of the chapters. Maybe this will help you - https://github.com/AnomalyInnovations/serverless-stack-com/issues/23#issuecomment-317851626

RaphaelMui commented 7 years ago

Thanks @jayair. Yes, I have more than 1 profile. The problem solved after I removed my AWS,SharedIniFileCredentials() codes.

jayair commented 7 years ago

@RaphaelMui I think we might need some conditional code in there to distinguish between the local and live cases.

neowulf commented 7 years ago

One can also pin the framework version by specifying the following line in the serverless.yml

frameworkVersion: "=1.17.0"

Serverless Documentation Link

neowulf commented 7 years ago

If you'd like to automate enabling the logs, you can follow this serverless config:

http://forum.serverless.com/t/how-to-enable-cloud-watch-logs-for-api-gateway-using-serverless/2067/2

jayair commented 7 years ago

@neowulf33 Good tips!