Link to chapter - http://serverless-stack.com/chapters/test-the-apis.html
Can you give us example screen shots to test API with postman using AWS signature? thanks in advance
@yashg5 I'm not too familiar with using Postman. Perhaps somebody else can give it a try.
First off, thanks a ton for your tutorials. I went through the previous and now the revised. You're doing great work.
For some reason I'm getting an error when testing the apis:
at new CognitoUserPool (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\amazon-cognito-identity-js\lib\CognitoUserPool.js:56:13)
at authenticate (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:70:18)
at Object.<anonymous> (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:155:1)
I can't really think of a reason why I would be experiencing this problem. I've had no problems for any of the tests I've done so far that used the same user-pool-id.
Any chance you could provide a sample apig-test call with actual values?
@marshallbunch Here is a sample one that I was using. I altered some of the values around but the format should be like so.
apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='us-east-1_YBhdXYvix' \
--app-client-id='29qwoeorti0ctjkur5h91lkw5g' \
--cognito-region='us-east-1' \
--identity-pool-id='us-east-1:565cc505-5486-4278-bf0f-9736p9apq8m5' \
--invoke-url='https://w5z1hluqmp5.execute-api.us-east-1.amazonaws.com/test' \
--api-gateway-region='us-east-1' \
--path-template='/notes' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'
No cigar. Won't make it past the user-pool-id.
@marshallbunch Hmm can I see the complete output from the command?
Sure:
C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\amazon-cognito-identity-js\lib\CognitoUserPool.js:56
throw new Error('Invalid UserPoolId format.');
^
Error: Invalid UserPoolId format.
at new CognitoUserPool (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\amazon-cognito-identity-js\lib\CognitoUserPool.js:56:13)
at authenticate (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:70:18)
at Object.<anonymous> (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:155:1)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
For beginners it might be helpful to specify that YOUR_API_GATEWAY_URL should include the stage-name (prod in the example).
"https://ly55wbovq4.execute-api.us-east-1.amazonaws.com/prod"
did that as well.
@marshallbunch Can you show me the full command you used as well? I'm not too familiar with the shell in Windows but let's take a look.
@manubhat90 Good catch. It would work either way but that can be confusing.
@jayair It is most definitely a syntax problem for the shell in windows. I got past the "invalid UserPoolId" error by getting rid of all the \ and the = and '. The current error is that it doens't like the json in the body content.
apig-test --username [email protected] --password Passw0rd! --user-pool-id us-east-1_HwIVtcRh2 --app-client-id 34bb7b87t6rtc387foiletrldf --cognito-region us-east-1 --identity-pool-id us-east-1:285f61b7-8a95-4596-90ce-7f7e1848c2ed --invoke-url https://6xosj8ww6h.execute-api.us-east-1.amazonaws.com/prod/words --api-gateway-region us-east-1' --path-template /words' --method POST --body {"content":"hello world","attachment":"hello.jpg"}
Authenticating with User Pool
Getting temporary credentials
Making API request
C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:31
throw err;
^
SyntaxError: Unexpected token c in JSON at position 1
at JSON.parse (<anonymous>)
at makeRequest (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:131:19)
at C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:114:5
at C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials.js:123:23
at Response.<anonymous> (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials\cognito_identity_credentials.js:258:7)
at Request.<anonymous> (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:364:18)
at Request.callListeners (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\sequential_executor.js:105:20)
at Request.emit (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\sequential_executor.js:77:10)
at Request.emit (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:683:14)
at Request.transition (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:22:10)
@marshallbunch Yeah I think we need to figure out how to format a string as an argument in the command line. And possibly escape the characters properly.
Hey guys. Great walkthrough. Everything went smoothly until it was time to test the API. I'm getting 502 bad gateway back from API Gateway. I looked in the CloudWatch logs and found that it can't import modules.
Unable to import module 'create': Error
at Function.Module._resolveFilename (module.js:469:15)
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:171:20)
I dug into this more by running the get lambda from the API gateway console dashboard using the test command. I got this:
Endpoint response body before transformations:
{
"errorMessage": "Cannot find module 'babel-runtime/regenerator'",
"errorType": "Error",
"stackTrace": [
"require (internal/module.js:20:19)",
"Object.<anonymous> (/var/task/list.js:76:18)",
"__webpack_require__ (/var/task/list.js:20:30)",
"Object.<anonymous> (/var/task/list.js:176:20)",
"__webpack_require__ (/var/task/list.js:20:30)",
"/var/task/list.js:63:18",
"Object.<anonymous> (/var/task/list.js:66:10)"
]
}
This led me to look into the file being uploaded to S3 by serverless deploy and found that they didn't include webpack. I've attached a screenshot of the unzipped file sent to S3 and the files built by using serverless webpack. As you can see, the node_modules folder is very different between them.

Some of the results of serverless deploy:
$ serverless deploy
Serverless: Bundling with Webpack...
Time: 1698ms
Asset Size Chunks Chunk Names
create.js 7.54 kB 0 [emitted] create
update.js 7.41 kB 1 [emitted] update
list.js 7.11 kB 2 [emitted] list
get.js 7.06 kB 3 [emitted] get
delete.js 6.84 kB 4 [emitted] delete
handler.js 3.35 kB 5 [emitted] handler
[0] external "babel-runtime/core-js/json/stringify" 42 bytes {0} {1} {2} {3} {4} {5} [not cacheable]
[1] external "babel-runtime/regenerator" 42 bytes {0} {1} {2} {3} {4} [not cacheable]
[2] external "babel-runtime/helpers/asyncToGenerator" 42 bytes {0} {1} {2} {3} {4} [not cacheable]
[3] ./lib/dynamodb-lib.js 652 bytes {0} {1} {2} {3} {4} [built]
[4] external "aws-sdk" 42 bytes {0} {1} {2} {3} {4} [not cacheable]
[5] ./lib/response-lib.js 721 bytes {0} {1} {2} {3} {4} [built]
[6] ./create.js 2.99 kB {0} [built]
[7] external "uuid" 42 bytes {0} [not cacheable]
[8] ./delete.js 2.37 kB {4} [built]
[9] ./get.js 2.58 kB {3} [built]
[10] ./handler.js 696 bytes {5} [built]
[11] ./list.js 2.61 kB {2} [built]
[12] ./update.js 2.9 kB {1} [built]
Serverless: Packing external modules: [email protected], [email protected]
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (14.28 KB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
......................................
Serverless: Stack update finished...
Service Information
service: notes-app-api
stage: prod
region: us-west-2
api keys:
None
endpoints:
---
functions:
create: notes-app-api-prod-create
list: notes-app-api-prod-list
get: notes-app-api-prod-get
update: notes-app-api-prod-update
delete: notes-app-api-prod-delete
Any help would be very much appreciated.
@tsdorsey Thanks for the details. As a quick sanity check, can I see your package.json and serverless.yml?
@jayair I should have done this before I posted.
https://github.com/tsdorsey/sls-notes-app
I have serverless-dynamodb-local and serverless-offline in my package file but I'm not using them at the moment. I planned to do that later.
@tsdorsey Good catch. It appears I'm experiencing the same issue.
@marshallbunch and @jayair I'm newish to webpack. Do you think you could point me in a direction so I could try to help figure this out? Got any gut feelings?
Ok, so I watched the folders as I ran serverless package and the .webpack folder is created with the dependencies in the node_modules folder as expected. Then the zip file is made and the .webpack folder is cleaned up. I have been reading through the package plugin; I'm suspect of the excludes directive but the aren't logged... :(
Getting 403 response
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } }
Yeah I get the same response...
{ status: 403,
statusText: 'Forbidden',
data: { Message: 'User: arn:aws:sts::907468717626:assumed-role/Cognito_notesidentitypoolAuth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-2:********7626:ux5xagukr9/prod/POST/notes' } }
I guess we forgot some tweaks that are not in the code, but rather in the aws console.
Ok, I got it working.
Basically, I deleted my Federated Identity Pool and recreated it from scratch following this section:
http://serverless-stack.com/chapters/create-a-cognito-identity-pool.html
Note that after doing so, I got these messes:
After that, I got correct 200 status.
Hope it helps
I'm not able to clear this test - if I put in all of my information in as a string, I get the cmd line response:
'Authenticating with User Pool
User does not exist'
Which makes no sense, because the user definitely exists - I created one with the same default credentials as in the example and a seperate one, which I used to create, update, delete the event.json file throughout the tutorial.
When I remove all the semi-colons from the data, it runs through saying:
'Authenticating with User Pool'
Getting temporary credential
Making API request
And then gives me the same JSON token error as the other commenter upstairs!
When I try just taking the string out the username and password, and keeping the rest of the strings there (and some variations) I get this error message:
Authenticating with UserPool
Getting temporary credentials
Inaccessible host: cognito-identity.xn--us-east-2-499dua.amazonaws.com'. This service may not be available in the‘us-east-2’' region.
However, from looking at AWS documentation, Cognito Identity should be available in US-East-2... Halp!
@tsdorsey I just tried your repo and I got it to deploy and call it fine. Of course the call failed because I don't have the IAM roles set up properly to do this. But It's calling everything fine.


I suspect there is something going on on your local. Can you try the following and check the versions you are running?

@marshallbunch Are you seeing the same error as @tsdorsey? If you go into your CloudWatch logs do you see the same error (Unable to import module 'create': Error)?
@Jonarod Yeah that error sounds like the IAM Role was not set properly. Thanks for reporting back with detail. I'm sure it'll help folks that run into something similar.
@navinkumarr Your issue sounds like the issue @Jonarod ran into. You can check if the IAM Role has been set properly by going to your AWS Console > IAM > Roles (in the sidebar) > Cognito_notesidentitypoolAuth_Role > Scroll down and click on Show Policy.

And make sure the policy looks like the one in the tutorial.
@mikhaelbendavid Are you on Windows as well like @marshallbunch? Can I see the full command you used that generated that last error?
@jayair I'm getting
{ status: 502,
statusText: 'Bad Gateway',
data: { message: 'Internal server error' } }
Digging deeper into Cloudwatch, specifically the create lambda function, I get
Unable to import module 'create': Error
at Function.Module._resolveFilename (module.js:469:15)
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)
My package.json is:
{
"name": "notes-app-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-3": "^6.24.1",
"glob": "^7.1.2",
"serverless-webpack": "^2.0.0",
"webpack": "^3.3.0",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"babel-runtime": "^6.23.0"
}
}
I haven't done any digging into the packaging that serverless deploy produces but this is to confirm I'm experiencing the same issue as @tsdorsey is experiencing.
@thesavvygreek Can I see what version of Node, NPM, and Serverless you are using?
@jayair Sure
@thesavvygreek @tsdorsey Thanks for that. Figured it out!
It's a Serverless Framework bug. They broke it with their latest release. Here is the issue somebody else opened for it - https://github.com/serverless/serverless/issues/3972
For now you can use 1.17.0 by doing the following. I'll add this to the tutorial.
$ npm uninstall -g serverless
$ npm install -g [email protected]
And then serverless deploy again.
@thesavvygreek Btw, your package.json is missing this line for some reason - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/package.json#L34
@jayair Ah nice one, it works! Thanks for the help!
I'm running into a 403 as well. I tried @Jonarod 's approach and carefully recreated the pool, but no dice.
I get this in the terminal:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } }
@jayair thank you so much for the thorough and quick help.
@marshallbunch did you get things squared away using this info?
I had a moment of horror when I moved to [email protected] and it still failed. Then I got to thinking about it and realized that I was using an environment variable for the region in my dynamodb-lib file. When I hard coded that to be us-west-2 The test came back successful. I know aws-lambda can do environment variables but I'll sort that out later.
For posterities sake I was running the following versions:
node -v 8.1.3
npm -v 5.0.3
serverless -v 1.18.0
@bradodarb Can you take a look at your Cloudwatch logs to see what it says? Also, can you post the IAM policy that you have (follow these instructions https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-317204545)?
Thanks for taking a look, @jayair.
I enabled logging on the API stage but see nothing in cloudwatch.
I did triple check my setting as you suggested and confirm that I have this inline role:
"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/*"
]
}
]
}
I tried switching the test parameters up a bit and instead of breaking the test url up between invoke-url and path-template as in the example I used the invoke-uRL from the API Gateway console and set the template to '/'
So instead of this:
apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='us-east-1_***********' \
--app-client-id='*************************' \
--cognito-region='us-east-1' \
--identity-pool-id='us-east-1:******************************************' \
--invoke-url='https://ps8mmgaj2c.execute-api.us-east-1.amazonaws.com/dev' \
--api-gateway-region='us-east-1' \
--path-template='/mail' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}
I tried this:
apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='us-east-1_***********' \
--app-client-id='*************************' \
--cognito-region='us-east-1' \
--identity-pool-id='us-east-1:******************************************' \
--invoke-url='https://ps8mmgaj2c.execute-api.us-east-1.amazonaws.com/dev/mail' \
--api-gateway-region='us-east-1' \
--path-template='/' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}
And I seemed to get more information back:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical
String for this request should have been\n\'POST\n/dev/mailC%3A/Program%2520Files/Git/\n\naccept:application/json\ncontent-type:application/json\nhost:ps8mmgaj2c.execute-api.us-east-1.amazonaws.com\nx-amz-date:2017
0724T154352Z\n\naccept;content-type;host;x-amz-date\n3a99f7c41ea871222ce9eb05cc8c7a5bbfc8e141bbb3c3999cff381d1462d448\'\n\nThe String-to-Sign should have been\n\'AWS4-HMAC-SHA256\n20170724T154352Z\n20170724/us-east-
1/execute-api/aws4_request\nb85c01d15750e6db44ea387c0ac4dec6bfd39b6cd8a245e32141e97b82955917\'\n' } }
This prompted me to have a look at all settings in the test parameters and everything validated to be using the correct variables.
@bradodarb The IAM Policy looks good. Can you post your serverless.yml as well? Let's make sure things look okay.
@jayair , I'm sure I'm doing/not doing something silly as I'm pretty novice with aws still. I really appreciate your help.
service: m4-user-mail-api
# Use serverless-webpack plugin to transpile ES6/ES7
plugins:
- serverless-webpack
# Enable auto-packing of external modules
custom:
webpackIncludeModules: true
provider:
name: aws
runtime: nodejs6.10
stage: dev
region: us-east-1
# 'iamRoleStatement' defines the permission policy for the Lambda function.
# In this case Lambda functions are granted with permissions to access DynamoDB.
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-1:*:*"
functions:
# Defines an HTTP API endpoint that calls the main function in create.js
# - path: url path is /mail
# - method: POST request
# - cors: enabled CORS (Cross-Origin Resource Sharing) for browser cross
# domain api call
# - authorizer: authenticate using the AWS IAM role
create:
handler: create.main
events:
- http:
path: mail
method: post
cors: true
authorizer: aws_iam
get:
# Defines an HTTP API endpoint that calls the main function in get.js
# - path: url path is /mail/{id}
# - method: GET request
handler: get.main
events:
- http:
path: mail/{id}
method: get
cors: true
authorizer: aws_iam
list:
# Defines an HTTP API endpoint that calls the main function in list.js
# - path: url path is /notes
# - method: GET request
handler: list.main
events:
- http:
path: mail
method: get
cors: true
authorizer: aws_iam
update:
# Defines an HTTP API endpoint that calls the main function in update.js
# - path: url path is /mail/{id}
# - method: PUT request
handler: update.main
events:
- http:
path: mail/{id}
method: put
cors: true
authorizer: aws_iam
delete:
# Defines an HTTP API endpoint that calls the main function in delete.js
# - path: url path is /mail/{id}
# - method: DELETE request
handler: delete.main
events:
- http:
path: mail/{id}
method: delete
cors: true
authorizer: aws_iam
The tutorial is great and must have already saved many 1,000s of person hours - thank you.
Unfortunately I have the same issue as @bradodarb. Always get a 404 when using apig-test. Have tried carefully recreating the identity pool. Pretty sure my IAM role/policy is correct. Must be something simple!
@bradodarb That looks good as well. The only thing I can do now is try out your code. Can you put it up on GitHub like @tsdorsey had done?
@jugglingcats Thanks for the kind words. The 404 seems like a different issue. Can I see the full output for the apig-test command?
Sorry I meant 403 Forbidden...
Same issue as @bradodarb @jugglingcats
apig-test. Here's my output:Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } }
@neowulf33 Thanks for the details.
Yeah you can turn on CloudWatch for API Gateway from the console under API Gateway. But it does not log some auth related errors. So I'm suspecting this is happening before it hits Lambda. The permission changes are not immediate but relatively quick. I'd say a couple of minutes.
Can you put up your repo? I want to try it out myself and see whats going on.
I'm getting an unauthorized response from this test and I'm not sure why. Anyone else get this, too?
{ status: 401,
statusText: 'Unauthorized',
data: { message: 'Unauthorized' } }
@jayair
Here's my repo:
https://github.com/bradodarb/m4-user-mail-api
@jayair Hi, Jayair. I'm preparing my tech talk on AWS lambda and following your tutorial. This is really helpful. Thank you so much.
I deployed the API ok. but testing API keeps giving me this error.
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
In cloudWatch logs it says
message: 'User: arn:aws:sts::721932120760:assumed-role/notes-app-api-prod-us-east-2-lambdaRole/notes-app-api-prod-create is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:us-east-2:721932120760:table/notes',
code: 'AccessDeniedException',
time: 2017-07-25T04:17:50.292Z,
requestId: '***********',
statusCode: 400,
my serverless.yml looks like this
service: notes-app-api # NOTE: update this with your service name
Use serverless-webpack plugin to transpile ES6 / ES7
plugins:
- serverless-webpack
Enable auto-packing of external modules
custom:
webpackIncludeModules: true
You can pin your service to only deploy with a specific Serverless version
Check out our docs for more details
frameworkVersion: "=X.X.X"
provider:
name: aws
runtime: nodejs6.10
stage: prod
region: us-east-2
you can add statements to the Lambda function's IAM Role here
'iamRoleSTatement' defines the permission policy for the Lambda function .
In this case Lambda functions are granted with permissions to access DynamoDB.
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-2:*:*"
I guess I hadn't figured it correctly about some permissions here but I can't find the reason why.
do you have any idea about this problem?
@jayair - Here is the full command:
Michaels-MacBook-Pro:serverlessblog Mikha-el$ apig-test \
--username=‘[email protected]’ \
--password='Passw0rd!' \
--user-pool-id='us-east-2_t6tTEb8QD' \
--app-client-id='52vsuvcodusl9lmeqcr4maq4ck' \
--cognito-region=‘us-east-2’ \
--identity-pool-id='us-east-2:a3fca15d-934a-4c40-915a-9a147e7010a4' \
--invoke-url='https://2mf1f9pxi7.execute-api.us-east-2.amazonaws.com/prod' \
--api-gateway-region=‘us-east-2’ \
--path-template='/notes' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'
Authenticating with User Pool
User does not exist.
My repo is here: https://github.com/mikhaelbendavid/serverlessblog
I'm on MacOS! I don't think there is anything wrong with my serverless.yml - I skipped ahead to the part where I am creating new notes to the API, and I am getting an issue that I have a TypeError: 'unable to fetch'
Also getting the same error as @bradodarb, @jugglingcats, and @neowulf33
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n\'POST\n/prod/notes\n\naccept:application/json\ncontent-type:application/json\nhost:1lu7ffc9hk.execute-api.us-west-2.amazonaws.com\nx-amz-date:20170725T140608Z\n\naccept;content-type;host;x-amz-date\n3a99f7c41ea871222ce9eb05cc8c7a5bbfc8e141bbb3c3999cff381d1462d448\'\n\nThe String-to-Sign should have been\n\'AWS4-HMAC-SHA256\n20170725T140608Z\n20170725/us-west-2/execute-api/aws4_request\nb672c9c637363a6d64ffdcdc78a2d76d7677b6cbf120411a8709a46ab27761e0\'\n' } }
Additional piece of info for me is that I was mid-way through the tutorial when the switch was made to use IAM as an authorizer. So I had to go back and make changes from looking at the PR. I wouldn't be at all surprised if I missed something.
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.
@bradodarb Just tried your repo. It worked fine for me.

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

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

@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.

@jugglingcats @limifont You guys can try the above as well and let me know how it goes.
@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.
@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.

@jcowley Thanks for reporting back!
for those having problems with windows cmd, this worked for me:
apig-test --username [email protected] --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\"}"
@algalvez Thanks for posting this. I'm sure it'll help!
@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?
@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.
@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...

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.
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.

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='[email protected]' \
> --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' } }
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!
@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.
@jugglingcats Can I try your repo as well? Just to make sure the issue isn't in the code.
@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.
@jayair
I used the following arn and seems to auth where it was not with '*'

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?
@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?
@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/*"
]
}
]
}
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='[email protected]' \
--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='[email protected]' \
--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')
_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?
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.
@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 - 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.
@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.
@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
@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
@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
@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.
@sidthe When you run the test from Lambda, do you mean in your local or through the AWS Console?
@jayair through the aws console
I did indeed need to downgrade my serverless version as @jayair mentioned:
$ npm uninstall -g serverless
$ npm install -g [email protected]
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='[email protected]' \
> --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!
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.
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!
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!!
@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.
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.
@clifftai Hmmm just to make sure you are using Serverless 1.17.0?
@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.
@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.
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.
@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.
@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\'' } } }
@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
Thanks @jayair. Yes, I have more than 1 profile. The problem solved after I removed my AWS,SharedIniFileCredentials() codes.
@RaphaelMui I think we might need some conditional code in there to distinguish between the local and live cases.
One can also pin the framework version by specifying the following line in the serverless.yml
frameworkVersion: "=1.17.0"
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
@neowulf33 Good tips!
When I log my apig-test in both the HTML request logging, and API request logging, I get no errors in the actual API Log, but in the HTML log I get ...
AccessDeniedException: User: arn:aws:sts::481588845003:assumed-role/hrs-admin-api-prod-ap-southeast-2-lambdaRole/hrs-admin-api-prod-create is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:ap-southeast-2:481588845003:table/notes
But the calls work fine from two chapters ago. I can create, update, edit, delete, etc... But I can't do it authorised from the apig_test. :(
@michaelcuneo That should be easy to fix. Can I see your serverless.yml?
In the past chapters we were invoking it directly using your local credentials. The apig-test is mocking how a user will be accessing it.
My serverless.yml is identical to the one as per the tutorial...
I did actually run through a bunch of issues that it could have been, I've added AWSLambdaRole and AmazonDynamoDBFullAccess permission to the Admin user I've created, but it didn't help. I'm using all the correct keys and secrets for that admin user, everything works 100% without auth, but fails with auth. Baffled. I've been on this issue for hours.
@michaelcuneo Yeah the issue is in your serverless.yml in this line.
Resource: "arn:aws:dynamodb:ap-southeast-2a:*:*"
It should be.
Resource: "arn:aws:dynamodb:ap-southeast-2:*:*"
You can see this in the error "...on resource: arn:aws:dynamodb:ap-southeast-2:481588845003:table/notes". It's looking for the table in the region ap-southeast-2.
Damn! It is too! I always forget that. Cause ap-southeast-2 has an a and b, but they both go to just 2.
Thanks! Works perfect now.
On a Mac w/serverless v1.19.0 I initially received the following output after running the apig-test command with good parameters:
Authenticating with User Pool
Getting temporary credentials
Invalid identity pool configuration. Check assigned IAM roles for this pool.
I confirmed I'd followed the Identity Pool instructs correctly, but noticed Authenticated and Unauthenticated roles had not been attached to my Identity Pool. After selected the Auth_Role from the Edit identity pool dropdown and creating a new Unauth_Role (just accepting the default policy json), and saving the changes, the same apig-test command worked as expected.
Did I miss something in the instructions, or are additional instructions needed?
@pjamieson You should not have to do that. It should be attached. I wonder if it didn't get saved properly the first time around. How did you find out that they weren't attached? Can you show me a screenshot? Thanks.
@jayair You are correct; it apparently was not saved correctly. I deleted my initial Identity Pool and the two associated IAM Roles, recreated the Identity Pool as per the instructions, and the roles are there as they should be. And the apig-test works as it should, too. All with serverless 1.19.0. Thanks! (Great turorial. I'm back after having done the prior version about two months ago. Thanks for pointing the way to Identity Pools.)
BTW, it seems that an apostrophe character (') in the content string breaks the apig-test command execution. (Just an FYI; I'm just removing it.) I see it's due to the body being enclosed in single quotes.
@pjamieson Thanks for reporting on 1.19.0. Just removed the 1.17.0 restriction.
I had the same apig-test error as @tsdorsey and deepseafishing above:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
with the following error being reported in CloudWatch:
message: 'User: arn:aws:sts::386757086157:assumed-role/notes-app-api-prod-us-west-2-lambdaRole/notes-app-api-prod-create is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:us-west-2:386757086157:table/notes',
code: 'AccessDeniedException',
time: 2017-08-11T03:03:28.333Z,
statusCode: 400,
It did turn out to be caused by the indentation in the serverless.yml file where the iamRoleStatements: were also indented at the same level as provider: instead of one level lower and therefore got ignored without error.
Properly indenting that section with tabs fixed the problem and apig-test now successfully reported:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 200,
statusText: 'OK',
data:
{ userId: 'us-west-2:c25c8604-477a-4eeb-921f-dcb2ea30ebe9',
noteId: '66f305b0-7e47-11e7-81ba-45b2b0dbb6ab',
content: 'hello world',
attachment: 'hello.jpg',
createdAt: 1502423079307 } }
running on Mac OS X 10.12.6 with:
node v6.11.1
npm 3.10.10
aws-sdk 2.95.0
webpack 3.5.3
serverless 1.19.0
Thanks you for this tutorial.
Thanks for reporting back @gregt590. The indenting issues causes a lot of headaches for folks.
PLEASE HELP!! I have read through the tutorial very carefully and have been struggling over this for so long.
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">\n<TITLE>ERROR: The request could not be satisfied</TITLE>\n</HEAD><BODY>\n<H1>ERROR</H1>\n<H2>The request could not be satisfied.</H2>\n<HR noshade size="1px">\nBad request.\n<BR clear="all">\n<HR noshade size="1px">\n<PRE>\nGenerated by cloudfront (CloudFront)\nRequest ID: 21E5qKTlLx8RJytknBwPbE9kFWg3CNUxFLD_N3xMhAhO7BpxiTzKhg==\n</PRE>\n<ADDRESS>\n</ADDRESS>\n</BODY></HTML>' }
@jeffxie888 It looks like we might be hitting the wrong URL? Can I see the full apid-test command?
I get 403 Bad Signature response too in various of my endpoints. I've tried to put the whole URL in invoke_url and it didn't help me:
{ status: 403,
statusText: 'Forbidden',
data: { message: 'The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n\'GET\n/dev/feed\npage=0&page_size=10\naccept:application/json\nhost:wex1vzo67b.execute-api.us-east-1.amazonaws.com\nx-amz-date:20170814T172052Z\n\naccept;host;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\'\n\nThe String-to-Sign should have been\n\'AWS4-HMAC-SHA256\n20170814T172052Z\n20170814/us-east-1/execute-api/aws4_request\nb53eba78268cf91932fa865871dd575a129681dcd4d3a9e79a676034efa1c419\'\n' } }
However, I may have found a pattern. I created a new service and started deploying each endpoint separately so I could find the reason of fails:
xxxx/users/id/123 Works finexxxx/users/email/[email protected] Doesn't workxxxx/users/[email protected] Doesn't workxxxx/feed?page=0&page_size=10 Doesn't workI tried to transform special characters into URL valid characters and still didn't work. Then I tried to search for testtest.com and I got a 404 as expected. And feed without page information returns 500 as expected too.
I'm currently moving all that information to body in requests, but that forces me to only use POST as requests method.
Is there a way to use special characters in URLs and don't getting 403 Bad Signature as response?
Thank you and thank you for this awesome tutorial 👍
@Cotel Thanks for details.
Case 3 & 4 contain querystring parameters that need to be passed in as an object into the additional-params option ({page:0,page_size:10}). For case 2, since we need the email part encoded we can send that in as a part of the params as well. So it could look like /users/email/{emailId} and the params option would be {emailId:"[email protected]"}. Give that a try and let me know how that goes.
For apig-test we internally use the https://github.com/kndt84/aws-api-gateway-client, and they have an example on how to use these options as well. We could work on making this more user friendly though.
I just tried to replace the params and now it is working as expected! Thank you 💯
@Cotel 👌
Once you get to the frontend portion you would need to do something similar. Let me know how that goes.
I'm now making the react part and it returns the same error as when testing with the cli tool:
export const getDatabaseUser = (email, userToken) =>
invokeApig({
path: `/users/email/${email}`
}, userToken)
I am sure the userToken is arriving correctly to this method. Configuration is set properly and the IAM role simulation allows me to invoke the Api. awsLib.js and sigv4Client.js is copy paste from the tutorial...

The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.The Canonical String for this request should have been'GET/dev/users/email/test%40test.comaccept:application/json↵host:wex1vzo67b.execute-api.us-east-1.amazonaws.comx-amz-date:20170817T183520Zaccept;host;x-amz-datee3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'The String-to-Sign should have been'AWS4-HMAC-SHA25620170817T183520Z20170817/us-east-1/execute-api/aws4_request57959ea0b29bcb252d83b38d563e3b3e67684f8eba45439fdf1f4ea21f69f856'"
in windows command line, should remove all double quotes, like --username=myname
for the value in json format, it should be look like this:
--body="{\"content\":\"hello world\", \"attachment\":\"dog.jpg\"}"
@everrr1025 Thanks for letting us know. I'm thinking of putting together a separate chapter on the differences for Windows.
@Cotel I thought I had replied to your comment but I think I must have not sent it.
The email that you are passing in as a part of the path needs to be URL encoded. Instead of [email protected], it needs to be test%40test.com. You can do this by hand or your can use something like https://github.com/bramstein/url-template.
i am on windows and i get 403 forbidden, i have readed all comments until the end, installed version 1.17 , copy pasted the yml file, changed ' with ", on my local machine i can invoke the functions, on the IAM simulator i can invoke the Amazon API Gateway, but the apig-test still doesnt work for me.
Is this test necesary to continue the rest of the tutorial? can i continue even if apig-test failed?
@Spartano Can I see the full command and the error message you are seeing? If it doesn't work here it most likely won't work down the road.
@jayair
```
apig-test --username [email protected] --password Passw0rd! --user-pool-id eu-west-1_xxxx --app-client-id 5baajsxxxxx --cognito-reg
ion eu-west-1 --identity-pool-id eu-west-1:bxxxxxx4-ad01-9e72a51c2b0f --invoke-url https://rxxxxxxni.execute-api.eu-west-1.amazonaws.com/prod
--api-gateway-region eu-west-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' } }
package.json
{
"name": "notes-app-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"aws-sdk": "^2.95.0",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-3": "^6.24.1",
"glob": "^7.1.2",
"serverless-webpack": "^2.2.0",
"webpack": "^3.5.2",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"babel-runtime": "^6.25.0",
"uuid": "^3.1.0"
}
}
```
What are the steps that one could make to debug this problem?
When i created the
From my point of view id love to see a extra tutorial on debugging the API calls, like the IAM Simulator and enabling CloudWatch Logs and how to use them.
@Spartano Yeah a debugging related chapter is definitely on our list.
So far what you posted looks good. But you'd generally start by looking at your CloudWatch logs to see where the 403 is being returned. Let me know if you've done that already.
Also, double checking your serverless.yml. So if you could post that as well.
@jayair so, to wrap up, i can invoke the functions from my local development, and in my CloudWatch i dont get any error, it seems like the calls never get to the cloud.
service: reviso-time-tracking
# Use serverless-webpack plugin to transpile ES6/ES7
plugins:
- serverless-webpack
# Enable auto-packing of external modules
custom:
webpackIncludeModules: true
provider:
name: aws
runtime: nodejs6.10
stage: prod
region: eu-west-1
# 'iAmRoleStatement' defines permission policy for Lambda function
# We are granting Lambda functions permission to access Dynamo DB
iAmRoleStatement:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:eu-west-1:*:*"
functions:
#Defines an HTTP API endpoint that calls the main function in create.js
# - path: rul path is /notes
# - method: POST request
# - cors: enabled CORS for browser cross domain API calls
# - authorizer: authenticate using the AWS IAM role
create:
handler: create.main
events:
- http:
path: notes
method: post
cors: true
authorizer: aws_iam
get:
#Defines HTTP API endoing that calls main function in get.js
# - path: url path is /notes/{id}
# - method: GET request
handler: get.main
events:
- http:
path: notes/{id}
method: get
cors: true
authorizer: aws_iam
list:
handler: list.main
events:
- http:
path: notes
method: get
cors: true
authorizer: aws_iam
update:
handler: update.main
events:
- http:
path: notes/{id}
method: put
cors: true
authorizer: aws_iam
delete:
handler: delete.main
events:
- http:
path: notes/{id}
method: delete
cors: true
authorizer: aws_iam
@Spartano That also looks okay. I think the 403 is coming from API Gateway. API Gateway logs are not on by default and are a little trickier to turn on. Can you try this - https://kennbrodhagen.net/2016/07/23/how-to-enable-logging-for-api-gateway/ and see if you get something in the logs?
@jayair i am making some progress, the problem was in the syntax of the apig code, since i am on windows.
I am using Visual Code and i have bash integrated, so i have wrongly presumed that i could use the same syntax. When i changed terminal, i was finaly able to see the errors inside the terminal and in the cloud watch.
in one of the above comments there is a command for windows, but the problem was it was missing some empty spaces. The correct command that worked for me was this:
apig-test --username [email protected] --password Passw0rd! --user-pool-id eu-west-1_pxxxxGN --app-client-id 5bxxxxxg29iudh93 --cognito-region eu-west-1 --identity-pool-id eu-west-1:398cxxxxxx9adf1037 --invoke-url https://vxxxxvj.execute-api.eu-west-1.amazonaws.com/prod/ --api-gateway-region eu-west-1 --path-template notes --method POST --body "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}"
now i am getting is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:eu-west-1
it will be really nice a guide on how to test it with Postman or another service, so it doenst matter what OS you are using.
@Spartano That makes sense. Thanks for trying to debug it more.
I just noticed that there is a typo in your serverless.yml. It should say iamRoleStatements instead of iamRoleStatement; like so https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/serverless.yml#L17.
Have this problem with status: 500:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
The problem was in serverless.yml fiile under the line
Resource: "arn:aws:dynamodb:us-west-2:*:*"
The was the wrong region because I don't change it from the example's one.
When I change region i receive
{ status: 200,
statusText: 'OK',
data:
{ userId: 'us-west-2:adb2febb-8fae-4745-98b6-4481cb8655d1',
noteId: 'f1962400-89a4-11e7-8c05-5928f46acd0b',
content: 'hello world',
attachment: 'hello.jpg',
createdAt: 1503672717889 } }
I also downgrade the serverless as was mentioned in previous comments.
@jayair Please add part in tutorial on proper region settings. I came across this problem in earlier chapters but was able to notice it. This one with api deploying gave me some pain.
@SeanSilke Thanks for reporting back. Yeah I'll add a note in the parts that need a region change.
I was experiencing the same errors as @tsdorsey and @thesavvygreek - 502 Bad Gateway and Unable to import module 'create': Error being reported in the CloudWatch logs.
fixed it by:
Unable to import module errortldr; check your package.json and ensure that babel-runtime is listed under dependencies. If it isn't, yarn add babel-runtime and redeploy serverless
also, per the linked issue's discussion thread, make sure that
custom:
webpackIncludeModules: true
is included in your serverless.yml (it should be if you configured serverless as described in the tutorial)
@zacacollier Thanks for the really detailed report back. I'm working on a chapter for debugging and your feedback will help with that.
@zacacollier You don't need to downgrade to serverless 1.17.0.
I am using 1.21.0 and it works just by adding babel-runtime in dependencies.
Great find man. thanks
@bumblebeen Yeah if I recall, it was 1.18 that was giving folks problems.
When running apig-test I get the following error:
Authenticating with User Pool
/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/request.js:31
throw err;
^
TypeError: callback.newPasswordRequired is not a function
at /usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/amazon-cognito-identity-js/lib/CognitoUser.js:281:27
at Response.<anonymous> (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/amazon-cognito-identity-js/lib/CognitoUser.js:249:18)
at Request.<anonymous> (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/request.js:364:18)
at Request.callListeners (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/usr/local/lib/node_modules/aws-api-gateway-cli-test/node_modules/aws-sdk/lib/request.js:38:9)
@paolini It looks like you might have created this user through the AWS Console? In this case the user is required to set a password when they first login. The apig-test CLI does not handle this case and expects that the user credentials are valid and can be used.
Yes thanks, that's the case... Seems there is no way to change or confirm the password from the aws console.
My next issue: IdentityPool not found.
I checked that the identityPoolId is correct:
$ aws cognito-identity list-identity-pools --max-results 10
{
"IdentityPools": [
{
"IdentityPoolName": "notes identity pool",
"IdentityPoolId": "eu-central-1:554ec0d7-0cd3-41e5-b5f9-cad20d34XXXX"
}
]
}
$ apig-test --username=pippo --password=password --user-pool-id=eu-central-1_3w4UEXXXX --app-client-id 267es0fnrdurq91phh2afnXXXX congnito-region eu-central-1 --identity-pool-id eu-central-1:554ec0d7-0cd3-41e5-b5f9-cad20d34XXXX --invoke-url https://9goegkXXXX.execute-api.eu-central-1.amazonaws.com/prod --path-template notes --method POST --body {"content":"hello world"}
Authenticating with User Pool
Getting temporary credentials
IdentityPool 'eu-central-1:554ec0d7-0cd3-41e5-b5f9-cad20d34XXXX' not found.
@paolini Just glancing at your command. Shouldn't the congnito-region should be --congnito-region?
Thanks again. You are right! Now I reduced my problem to 403 Forbidden... :-(
I tried everything that I can and could not find anything wrong. the serverless.yml is same as posted here. but when I am test, I always got 403 error. it is running on Windows 7 and below is the output.
apig-test .............................
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } }
D:\app-api>serverless -v
1.17.0
D:\app-api>npm -v
5.4.0
D:\app-api>node -v
v6.11.2
@u8006082 If you are on Windows, @Spartano's comment https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-324556718 from above might help you. I think he was having the 403 error before as well.
@paolini @u8006082 Another thing to make sure to try is the IAM policy simulator - https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-317821887.
Thanks Jayair! I missed "/" after prod. it should be https://hyuzdjsm1e.execute-api.us-east-1.amazonaws.com/prod/
by the way for window user you can use ^ (unix is ) to separate the line.
I am running the following command and getting an error:
apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='us-west-2_*********' \
--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='/notes' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'
Error:
Inaccessible host:cognito-identity.xn--us-west-2-**.amazonaws.com'. This service may not be available in the ‘us-west-2’' region.
I've done some searching on this and am not finding a solution. Anybody familiar with this issue?
@samxi Hmmm that seems strange. The only thing I can think of here is to double check the Cognito id's that are being set and make sure that the region info for them is correct.
@samxi there is no space after each comand correct: "apig-test/space"
not vorrect:"apig-testspace/space"
@jayair @Spartano
I removed the space before \ on my invoke command and got a new error:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { Message: 'User: arn:aws:sts::904892619278:assumed-role/Cognito_notesidentitypoolAuth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-west-2:********9278:zgbqusr8ua/prod/POST/notes' } }
I tried @Jonarod 's suggestion and deleted my initial identity and created a new identity. Now I am getting a 500 error:
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
The command I am using was updated to the new identity ID:
apig-test --username='[email protected]' --password='Passw0rd!' --user-pool-id='us-west-2_XOwARY4ea' --app-client-id='6k30s80bm1agn9c1pbjdhnn1p3' --cognito-region='us-west-2' --identity-pool-id='us-west-2:b1a93438-17a6-4c6c-91a2-31b4883da2a8' -
-invoke-url='https://zgbqusr8ua.execute-api.us-west-2.amazonaws.com/prod' --api-gateway-region='us-west-2' --path-template='/notes' --method='POST' --body='{"content":"hello world","attachment":"hello.jpg"}'
My Auth_Role policy for the role in IAM is:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics:PutEvents",
"cognito-sync:*",
"cognito-identity:*"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::sambb-notes-app-uploads/${cognito-identity.amazonaws.com:sub}*"
]
},
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-west-2:*:zgbqusr8ua/*"
]
}
]
}
Not sure what else I am missing. I set up a new role for CloudWatch logging but am not sure how that works.
@samxi the syntax of --invoke is wrong, and double check the .yml syntax with the one from the guide.
apig-test --username [email protected] --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 @Spartano
Rolling through all of the files/settings again I found a couple discrepancies and was able to get things working properly. Reading through these comments and all of your suggestions has helped me better understand the whole system and improve my troubleshooting skills.
Thank you both for your quick responses and help!
@jayair I am getting following error:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } }
I've tried everything (double checking my .YML file, policy, policy simulating, etc) but nothing works for me. Can you please help me with this issue? Following is my github repo:
https://github.com/nvamshik/notes-app-api
@nvamshik what OS are you using?
@Spartano I'm using Windows 8.1
Did you use the syntax for windows users from the guide? Can you paste it here please.
I used the windows syntax.
apig-test --username [email protected] --password Passw0rd! --user-pool-id us-east-1_TXj0SxE --app-client-id 3201ojaiiav0k0p5ais0op3m --cognito-region us-east-1 --identity-pool-id us-east-1:c3c3e453-c386-4e59-b689-525bebc07 --invoke-url https://knl827x1si.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\"}"
@nvamshik I'm not sure if it's a typo but the --path-template that we use in the tutorial is /notes not notes.
I also get IdentityPool not found
Authentication is fine:
➜ serverless-stack-demo-api git:(master) ✗ apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='eu-west-2_achS8baFu' \
--app-client-id='6o3iivoaqbslnqatt46jche42e' \
--cognito-region='eu-west-2' \
--identity-pool-id='us-west-2:55f8e2df-7e47-4120-bdc0-843f2974f63b' \
--invoke-url='https://y85xk63wnk.execute-api.eu-west-2.amazonaws.com/prod' \
--api-gateway-region='eu-west-2' \
--path-template='/notes' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'
Authenticating with User Pool
Getting temporary credentials
IdentityPool 'us-west-2:55f8e2df-7e47-4120-bdc0-843f2974f63b' not found.
On AWS my pool is:
us-west-2:55f8e2df-7e47-4120-bdc0-843f2974f63b
arn:aws:cognito-identity:us-west-2:180971085012:identitypool/us-west-2:55f8e2df-7e47-4120-bdc0-843f2974f63b
Do pools and Identities need to be in the same region?
I moved the Id pool to eu-west-2 and new error: Invalid identity pool configuration. Check assigned IAM roles for this pool. I will investigate and report back

this is my permissions for the role assigned to this Id pool:

@QuantumInformation Can you following the steps in this comment (https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-317204545) to see what the policy is for your Identity Pool?
And post it here.
Sure
The Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics:PutEvents",
"cognito-sync:*",
"cognito-identity:*"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::notes-testtut/${cognito-identity.amazonaws.com:sub}*"
]
},
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:eu-west-2:*:y85xk63wnk/*"
]
}
]
}
I tested the policy against the s3 bucket, but it said access is denied:

The bucket exists: http://notes-testtut.s3.amazonaws.com/
I checked the policy for the api and it has access.
@QuantumInformation I might be a little confused here, so your React app is able to make requests to your API but you are not able to upload files to S3?
@jayair - I think some of these 403 and 500 errors are related to having aws profiles different than the default profile. I've redone this backend for the 3rd time today. First 2 goes I was not using the default profile in aws. This last time I set the aws configuration as the default. This time I didn't have a problem.
I hope this helps someone. Great tutorial really learning incredible amounts.
So the error I was having was due to the role not having the correct trusted entity or smth.

Now I am getting this after fixing the string condition to match the cognito id:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
➜ serverless-stack-demo-api git:(master)
@clarkgrg does apig-test use your profile? I don't think it does, it just behaves as a real user.
Detailed error: I think I can fix this:
message: 'User: arn:aws:sts::180971085012:assumed-role/notes-app-api-prod-eu-west-2-lambdaRole/notes-app-api-prod-create is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:us-east-1:180971085012:table/notes',
Ok I fixed it and its working now!
@QuantumInformation Do you mind leaving a comment saying what the issue you were seeing was and what you fixed. I think it'll help other folks. Thanks.
Will do, btw I'm live streaming this tut: https://go.twitch.tv/quantuminformation#
@QuantumInformation That's awesome. I'm going to tweet it out.
to fix my error I just had to update the policy file with the new location of the dyn DB table as it was the wrong region.
I don't believe apig-test uses your profile. I think only serverless deploy. If you use profiles serverless deploy has a --profile (or --profile-name) option, but I struggled to get that going.
@jayair @marshallbunch I was able to run the apig-test on Windows PowerShell. I used the following code and it worked:
apig-test --username [email protected] --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""}'
Can someone help me? I'm not sure where did I go wrong but when I run apig-test, I'm getting a 500 error failed status. Upon checking the console log, i'm getting this validation error:
[ValidationException: One or more parameter values were invalid: Type mismatch for key userId expected: S actual: NULL]
message: 'One or more parameter values were invalid: Type mismatch for key userId expected: S actual: NULL',
code: 'ValidationException',
time: Sun Oct 22 2017 09:17:00 GMT+0000 (UTC),
requestId: 'G4GBGG9CUEN1DSU7EH809DN6KJVV4KQNSO5AEMVJF66Q9ASUAAJG',
statusCode: 400,
retryable: false,
retryDelay: 8.820808271411806 }
It seems like that the event context that is being passed in the function has null userId. Based on the Identity pool console, I can see there that there's new identity but I don't know why I am getting a null userId.
Hope someone can help me with this.
@chaosdarky Is it the event.requestContext.identity.cognitoIdentityId that is null for you? Can you try to console.log and check which part of the event object is null?
Would someone help to debug an error? I have tried debugging, going through the whole process time after time, searching for solutions with AWS forums, but I'm still stuck on this one. I am getting
{ status: 502,
statusText: 'Bad Gateway',
data: { message: 'Internal server error' } }
response. here is the error from the log:
AccessDeniedException: User: arn:aws:sts::297650182091:assumed-role/bakery-api-prod-eu-central-1-lambdaRole/bakery-api-prod-create is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:eu-central-1:297650182091:table/products
(I have called my table and the app differently than in the tutorial).
What am I missing and where is this coming from? The API are working locally.
@jayair yes, the event.requestContext.identity.cognitoIdentityId is null. I tried to console log the event and the cognitoId there is null.
I resolved the AccessDeniedException by attaching a new inline policy for DynamoDB to my lambda function. The response status is 200 now.
However, the issue with the status: 502 persists. I'm pretty sure that I have the same callback as in the tutorial and JSON.stringify, but I am having the Execution failed due to configuration error: Malformed Lambda proxy response in the CloudWatch and cannot find what's the reason for it. Anyone?
@akolybelnikov That usually happens when the response object is not formatted properly. You can debug this by logging what this line returns - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/create.js#L20.
Re: Unexpected input for JSON body argument on Windows. Here's what worked for me:
'{\"content\":\"hello-world\",\"attachment\":\"hello.jpg\"}'
Doesn't seem to like the space in 'hello world'. I'm sure there's a way to escape it though.
@jayair While testing locally, it returns the 200 status like so:
{
"statusCode": 200,
"headers": "{\"Access-Control-Allow-Origin\":\"*\",\"Access-Control-Allow-Credentials\":true}",
"body": "{\"userId\":\"USER-SUB-1234\",\"productId\":\"011fce60-bb57-11e7-9592-2599999d8bb3\",\"category\":\"buns\",\"productName\":\"zimt-bun\",\"content\":\"Christmas flavoured airy bun\",\"attachment\":\"zimtbun.jpg\",\"price\":\"133.10 RUB\",\"createdAt\":1509136801350}"
}
It's when I'm testing it remotely that I get this back:
{ status: 502,
statusText: 'Bad Gateway',
data: { message: 'Internal server error' } }
The thing is that the data is being posted in the DynamoDB: I can see it. I have tried a lot of things, but I cannot get to the root of the problem. What's the way to see what exactly causes this behaviour? I don't get to see much more info at the CloudWatch either.
@akolybelnikov So using a console.log before the data is returned does not show anything in the CloudWatch logs?
Hi @jayair
here's what I get in CW:
(92123dc7-bb56-11e7-81fe-9d159db3aeda) Endpoint response body before transformations:
{
"statusCode": 200,
"headers": "{\"Access-Control-Allow-Origin\":\"*\",\"Access-Control-Allow-Credentials\":true}",
"body": "{\"userId\":\"eu-central-1:e393fcdf-4bba-4a36-b844-c8bfafc20fc7\",\"productId\":\"921c76d0-bb56-11e7-8c22-9b7368c0b402\",\"category\":\"bread\",\"productName\":\"Moscower\",\"content\":\"traditional loaf\",\"attachment\":\"loaf.jpg\",\"price\":\"103.98 RUB\",\"createdAt\":1509136615101}"
}
(92123dc7-bb56-11e7-81fe-9d159db3aeda) Endpoint response headers: {x-amzn-Remapped-Content-Length=0, Connection=keep-alive, x-amzn-RequestId=92188007-bb56-11e7-8447-a501c93e3a7a, Content-Length=409, Date=Fri, 27 Oct 2017 20:36:55 GMT, X-Amzn-Trace-Id=root=1-59f398e7-9fc85288e6a24722051885b7;sampled=0, Content-Type=application/json}
md5-0b63a88e9621ff7a62254ff15766149c
(92123dc7-bb56-11e7-81fe-9d159db3aeda) Execution failed due to configuration error: Malformed Lambda proxy response
md5-0b63a88e9621ff7a62254ff15766149c
(92123dc7-bb56-11e7-81fe-9d159db3aeda) Method completed with status: 502
It's 200 followed by 502.
@akolybelnikov If you check the tutorial, the headers need to be a JSON object not a string - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/libs/response-lib.js#L12
@jayair I must have changed that line trying to refactor the code,. I have changed the line back to the JSON object, it doesn't have any effect though, still getting the 502. We don't have to re-deploy once we change the code locally, do we?
issue resolved. I did not re-deploy after local changes. what was I thinking? don't ask me. getting proper response now.
Hi, i’m still getting the error. Hope someone can help to debug it.
@chaosdarky Can you check your Cognito User Pool and Identity Pool to check it there is a user in there? In the User Pool there should be a user with the email [email protected].
@jayair there are user there. I was able to authenticate and Identity Pool shows that i have 1 new identity so its working but I don’t know why I am still getting a null CognitoIdendityID
@chaosdarky And this happens even if you tried it as a new user? As in, create another user and try it again?
I got a 403 response:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } }
Then I followed @bradodarb's idea:
I changed this:
--invoke-url='https://xxxx.execute-api.us-west-2.amazonaws.com/prod'
--path-template='/notes'
to
--invoke-url='https://xxxx.execute-api.us-west-2.amazonaws.com/prod/notes'
--path-template=''
and my API testing worked.
@toyeebgodo Hmmm that's weird. But thanks for reporting!
Is it possible that "something" (perhaps a serverless deploy or a bug within AWS) somehow changed the policy document of the Auth role associated to the federated identity we created?
For some reason, I suddenly started getting the same error as certain people above: User: arn:aws:sts::904892619278:assumed-role/Cognito_notesidentitypoolAuth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-west-2:********9278:zgbqusr8ua/prod/POST/notes
When checking the policy document, it seemed like the wildcard was missing:

The thing is, I never removed it myself, and the wildcard certainly used to be there. Restoring it resolves the issue

But the real question is: what could have changed the policy document in the first place?
@tommedema That's really strange...
I am one of those getting a 502, but the details are different. I have read the discussion so far and tried relevant ideas for myself. On inspecting the logs I see this error, which has not yet been discussed:
(c1dc9b55-c4e3-11e7-ba33-6db69d7dccc2) Endpoint response body before transformations:
{
"errorMessage": "EACCES: permission denied, open '/var/task/create.js'",
"errorType": "Error",
"stackTrace": [
"Object.fs.openSync (fs.js:641:18)",
"Object.fs.readFileSync (fs.js:509:33)",
"Object.Module._extensions..js (module.js:578:20)",
"Module.load (module.js:487:32)",
"tryModuleLoad (module.js:446:12)",
"Function.Module._load (module.js:438:3)",
"Module.require (module.js:497:17)",
"require (internal/module.js:20:19)"
]
}
@lucasgonze That's pretty strange. I haven't seen that before but some Google searching shows that maybe it's related to the file permissions of create.js? Here is some more info:
@jayair, these links are a useful clue. My permissions turn out to be 600 rather than 644, probably because of the default mask in termux/android. I will debug from this hypothesis.
The EACCESS issue is very likely that permissions on create.js are 660 rather than 644 or 664. That is, only my user account and its unix group have read permission.
660 is an interaction with how zip works in termux. The issue is specific to termux.
This is probably unfixable. Other termux users can track (or vote for) the issue here:
https://github.com/termux/termux-packages/issues/1799
The best I can imagine serverless-stack and the Serverless framework doing is to warn termux users.
@lucasgonze Thanks for reporting back. It can be a tricky issue to track down.
Moving my code to a non-ChromeOS machine did fix the EACCESS problem.
After running serverless deploy for the first time. I got the same "CognitoIdentityCredentials is not authorized to perform: execute-api" error as @Jonarod, and solved it the same way, by creating a new Federated Identity Pool. The reason why this desparate measure works is that you can then edit the policy document, which has a hard coded reference to the gateway returned by serverless deploy.
I couldn't find another way to edit the policy document once it has been created, though I'm sure one exists.
After this I got 200 OK on my apig test.
Thank you for a superb guide!
Regarding @Spartano's comment from above. I am using Git Bash on Windows 10 and was getting the following:
$ apig-test
--username [email protected]
--password Passw0rd!
--user-pool-id us-east-1_VxxxM
--app-client-id 4xxxd
--cognito-region us-east-1
--identity-pool-id us-east-1:fxxx1
--invoke-url https://9xxxf.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' } }
By moving the slash from --path-template to --invoke-url it started working:
$ apig-test
--username [email protected]
--password Passw0rd!
--user-pool-id us-east-1_VxxxM
--app-client-id 4jxxxld
--cognito-region us-east-1
--identity-pool-id us-east-1:fdxxxb1
--invoke-url https://9xxxf.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: 200,
statusText: 'OK',
data:
{ userId: 'us-east-1:4xxx3',
noteId: 'exxxf',
content: 'hello world',
attachment: 'hello.jpg',
createdAt: 1511260183884 } }
Created a pull request and added this tip to the 403 troubleshooting section.
@johnnybigert Thank you for this.
I'm getting the following response after issuing the initial apig-test command:
Authenticating with User Pool
Unexpected key 'UserContextData' found in params
Any idea what this might be?
@fpoumian Can I see the full command that you are using?
Does anyone know where I may be going wrong?
It says tthe JSON object, but earlier when I had the JSON arg wrong, it errored out before it authenticated with the user pool etc
This is my input
apig-test
--username [email protected]
--password Passw0rd!
--user-pool-id us-east-2_xxxxC
--app-client-id 7xxxe
--cognito-region us-east-2
--identity-pool-id us-east-2:7xxxxb
--invoke-url https://dnxxxxd.execute-api.us-east-2.amazonaws.com/prod
--api-gateway-region us-east-2
--path-template /notes
--method POST
--body "{"content":"hello world","attachment":"hello.jpg"}"
This is the output I get

@svj13 There's an issue in your escaping of the --body argument. Replace the outer double quotes with singles.
@lucasgonze replacing with single quotes, removing/adding escape characters etc all come up with the same error
I could copy up all of the inputs I've tried to see if anything can be spotted that I'm doing wrong
Can you modify index.js:160 to log what it's trying to parse?
@lucasgonze

Fellow 403 errors, check your IAM policy for Auth users.
I had included an accidental space and was getting the 403
Cognito_notesidentitypoolAuth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke
Have you considered using making aws-api-gateway-cli-test a local dev dependency and then invoking the local package using 'npx'? For people who are hesitant to install packages globally, this would be a nice tweak to the tutorial
I only figured this one out now, i'm having difficulties with our proxy but already created a new ticket for it: https://github.com/AnomalyInnovations/serverless-stack-com/issues/175
In case this might help somebody;
const userDetails = {
USERNAME: "test",
PASSWORD: "password",
};
const args = [
"--username", userDetails["USERNAME"],
"--password", userDetails["PASSWORD"],
"--user-pool-id", output.UserPool,
"--app-client-id", output.UserPoolClient,
"--cognito-region", output.Region,
"--identity-pool-id", output.IdentityPool,
"--invoke-url", output.ServiceEndpoint,
"--api-gateway-region", output.Region,
"--path-template", "/notes",
"--method", "POST",
"--body", "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}"
];
spawn("./node_modules/.bin/apig-test", args).stdout.pipe(process.stdout);
@evangow Yeah that's a good idea. I'll take a look into it.
@d0ruk That looks interesting. What does this bit of code do?
@jayair repo
It maps the stack outputs to the apig-test CLI.
How do I copy this into my terminal... everytime I copy and paste my code in, it just adds a > for each new line... I can never run the code :(
It looks like this no matter what I do and then when I try to clear the console it just adds another > and a new line... how do i escape this?
Here's my code:
apig-test\
--username='[email protected]'\
--password='Passw0rd!'\
--user-pool-id='us-east-2_AxxxxfBnL'\
--app-client-id='4vt88xxxxxxvv6cubd'\
--cognito-region='us-east-2'\
--identity-pool-id='us-east-2:3d8xxxxxxxe9982253f'\
--invoke-url='https://akse8rq9w0.execute-api.us-east-2.amazonaws.com/prod'\
--api-gateway-region='us-east-2'\
--path-template='/notes'\
--method='POST'\
--body='{"content":"hello world","attachment":"hello.jpg"}'\
If i then go in and delete all the > I also get this error:
Invalid UserPoolId format.
@JackEdwardLyons Are you on OS X or Windows?
i'm on Mac OS X -- sorry I should have mentioned that above. Here's the code I am running, which does actually run now, but I get an error saying incorrect username or password even though they are exactly the same as the example in the earlier chapter:
apig-test [email protected] --password=Passw0rd! --user-pool-id=us-east-2_akse8rq9w0 --app-client-id=4vt88hu5be99xxxxxx6cubd --cognito-region=us-east-2 --identity-pool-id=us-east-2:3d82638c-ba44-43xxxxe-40ae9982253f --invoke-url=https://akse8rq9w0.execute-api.us-east-2.amazonaws.com/prod --api-gateway-region=us-east-2 --path-template=/notes --method=POST --body='{"content":"hello world","attachment":"hello.jpg"}'
Hi, I am also getting the 502 error, but none of the above solutions proved helpful.
I think it has something to do with how the code is transpiled, because I can see the following error in cloudwatch:
Syntax error in module 'list': SyntaxError
async function main(event, context, callback) {
^^^^^^^^
SyntaxError: Unexpected token function
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
I got this error before when I was testing the api calls locally with serverless. It turned out I was using an older version of node and upgrading to 8.9.3 resolved that issue.
I am using the following versions of the tools:
serverless -v 1.17.0
node -v 8.9.3
npm -v 5.6.0
Could you please help me figure this out?
Ok I'm getting closer. I managed to add a config to iTerm2 to allow copy and pasting into the terminal and not running the command immediately > you can read the post here <
Now, I get an error Incorrect username or password even though I have created the user as listed in the earlier chapter.... Not sure what to do from here. I even created another user and confirmed / enabled it, but it still says Incorrect username or password
@JackEdwardLyons I'm not sure what is going on with iTerm2 in this case but for this chapter - https://serverless-stack.com/chapters/create-a-cognito-test-user.html; can you ensure that you are creating a user with the password correctly?
Instead of copying and pasting can you try typing in the command yourself to make sure that it is being created correctly?
@jefaramvangorp It seems like your code is not being transpiled properly. Can you check if you've completed this chapter - https://serverless-stack.com/chapters/add-support-for-es6-es7-javascript.html?
@jayair Thanks for your response. I found my error while I was typing a reply to your question. I feel really dumb now, but it turned out that I had added the babel config file as babelrc instead of .babelrc (note the dot in the second name). Renaming the file fixed the issue.
I also got the "status: 403" when testing my API, however thanks to the great people working with "serverless-stack" I found my way to a solution (although it took some trial and error). To help others I paste my documented log of what I did to resolve the issue below.
My initial response ->
Response ->
{ status: 403,
statusText: 'Forbidden',
data:
{ Message: 'User: arn:aws:sts::477655596505:assumed-role/Cognito_cjnotesAuth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-1:********6505:xxxxxxxxxx/prod/POST/notes' } }
My Log to resolution ->
Cognito Identity -> Role name -> `cjnotes`
Authenticated role -> `Cognito_cjnotesAuth_Role`
Open IAM Policy simulator-> https://policysim.aws.amazon.com/home/index.jsp
Click to select **Roles** (not **Users**)
Selected role -> `Cognito_cjnotesAuth_Role`
Service -> **API Gateway**
Action -> **Invoke**
Expand **Amazon API Gateway** row
Paste API gateway endpoint -> `arn:aws:execute-api:us-east-1:*:xxxxxxxxxx/*`
Click button **Run Simulation**
Response i policy simulator ->
Amazon API Gateway
Invoke
execute-api-general
execute-api-general
**denied**
NOW I HAVE VERIFIED PERMISSION IS NOT OK FOR MY ROLE (Authenticated role -> `Cognito_cjnotesAuth_Role`)
I NEED TO FIX THIS ->
In AWS console open IAM- > https://console.aws.amazon.com/iam/home?region=us-east-1#/roles
Click on the role -> `Cognito_cjnotesAuth_Role`
Expand policy row
Click **Edit policy**
Click tab **JSON**
Edit policy ->
(bold is the changed stuff) ->
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics:PutEvents",
"cognito-sync:*",
"cognito-identity:*",
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:*:xxxxxxxxxx/*"
]
}
]
}
(replace xxxxxxxxxx with your value)
Click Review Policy
Click Save Changes
I RUN AGAIN
In terminal ->
apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='us-east-1_xxxxxxxxx' \
--app-client-id='dmfq6no2nhqshakvfbueinos2' \
--cognito-region='us-east-1' \
--identity-pool-id='us-east-1:c8b8e333-9d52-4c41-9e91-xxxxxxxxxxxx' \
--invoke-url='https://xxxxxxxxxx.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"}'
Response ->
{ status: 200,
statusText: 'OK',
data:
{ userId: 'us-east-1:xxxxxxxx-0c52-402f-8f6f-09f163b08735',
noteId: 'eb4d3f50-09bc-11e8-ab2c-b9edda96b9fd',
content: 'hello world',
attachment: 'hello.jpg',
createdAt: 1517756764101 } }
@topguncharl Thank you very much for adding in detail your debug process. It will help a lot of other folks that are going to go through it. I formatted it a bit with some Markdown for clarity.
@jayair Hello it's me again, sorry to bother you again.
I am getting the following error now
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
I've tried to navigate through the comments having the same error, I went back to the 1.17.0 serverless version, and then I couldn't re-deploy because I got an error about updating Lambda. The CloudWatch logs don't say too much either.
@ivanms1 This is an error we generate in our Lambda. So you can add console.log in the Lambda to debug what is going on. The logs will show up in CloudWatch.
@jayair by Lambda you mean the create, delete, etc functions?
@ivanms1 Yeah it is in those functions that we generate this error. For example, for the get case we generate it here - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/get.js#L25
So you could add some debug messages before that line to see what is going on.
@jayair I already have a console.log in all those functions, maybe I set up the CloudWatch wrong, I still get logs tho. I don't see an error message anywhere
(dd007ab9-12ca-11e8-b201-8fec456d096a) Verifying Usage Plan for request: dd007ab9-12ca-11e8-b201-8fec456d096a. API Key: API Stage: binkm6jb4m/prod
(dd007ab9-12ca-11e8-b201-8fec456d096a) API Key authorized because method 'POST /notes' does not require API Key. Request will not contribute to throttle or quota limits
(dd007ab9-12ca-11e8-b201-8fec456d096a) Usage Plan check succeeded for API Key and API Stage binkm6jb4m/prod
(dd007ab9-12ca-11e8-b201-8fec456d096a) Starting execution for request: dd007ab9-12ca-11e8-b201-8fec456d096a
(dd007ab9-12ca-11e8-b201-8fec456d096a) HTTP Method: POST, Resource Path: /notes
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method request path:
{}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method request query string:
{}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method request headers: {Accept=application/json, x-amz-date=20180216T033833Z, CloudFront-Viewer-Country=TH, CloudFront-Forwarded-Proto=https, CloudFront-Is-Tablet-Viewer=false, CloudFront-Is-Mobile-Viewer=false, User-Agent=axios/0.17.1, X-Forwarded-Proto=https, CloudFront-Is-SmartTV-Viewer=false, Host=binkm6jb4m.execute-api.us-east-2.amazonaws.com, x-amz-security-token=AgoGb3JpZ2luEKP//////////wEaCXVzLWVhc3QtMiKAAlTmYUda+bA65tBI6dCcB4aubUmGzAvAvBeZubcXXl/z0PWg5aoZ/G6FrFlfWcgKy9XxiB8wKvVaZDVbdULvE6NF0LoLIIstPS5wlthyEk8VSM3oYAGfqvQvZ9NW/NM0VzKeegM2zi0bQg10Az9XBdDzYIMGeMSbnE41dZ/T7kcPvs1veqGpBxHYA5+PooAInky7VgotOCv9FAvXwLoRQqN4R51jYYEcI+SDyg1y42MmD12xdB5RAc4rzfCZ9zSwDnWlyAHXDqBCuNb0FXlXUs051IyjCUzRliG5rXHz+UZSgpRjQTPMmJVQl9wCIba3cwmg3bDfvKOCy9c++mLUvT8qrwUInf//////////ARAAGgw1MDMxNzk5Nzc2NzgiDLCgFaM9V4ntI9euVyqDBcC0PktYfMUGtWkItZAPiS3+VNZE2iZV2r3mG5sv6X9USewMpzN4Uu8E1M4Cy7mczVoZDdRx0a+CLph8kJjzk9m5HnavbKMtBgo1YbpG9Pd6+Rx9hWpLGapZ2DjIfwk+zTPAmn+1xbXyTsoFOG+xmmp7x1wBsjXv4byyXExSSvgmK78Z7R8IW4o5rGI6fd9zlq7mUM2ETJk [TRUNCATED]
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method request body before transformations:
{
"content": "hello world",
"attachment": "hello.jpg"
}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Endpoint request URI: https://lambda.us-east-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-2:503179977678:function:notes-app-api-prod-create/invocations
(dd007ab9-12ca-11e8-b201-8fec456d096a) Endpoint request headers: {x-amzn-lambda-integration-tag=dd007ab9-12ca-11e8-b201-8fec456d096a, Authorization=************************************************************************************************************************************************************************************************************************************************************************************************************************869208, X-Amz-Date=20180216T033833Z, x-amzn-apigateway-api-id=binkm6jb4m, X-Amz-Source-Arn=arn:aws:execute-api:us-east-2:503179977678:binkm6jb4m/prod/POST/notes, Accept=application/json, User-Agent=AmazonAPIGateway_binkm6jb4m, X-Amz-Security-Token=FQoDYXdzEJz//////////wEaDBGNrv8zmtc8+GkAuyK3A3BP+66txghNqIn+He/DVAwvbYw/WYdLoPR9/l02bBQvMGn6OpMwDReEnuq+A5W4iYxCH1Nx1+kG249YCZP1bgoDHEea+7oMluDiJoZxKepPXWNJlIKMSni2Mo2Yga0QjUX4kNdSB7BUz95TXTvX28UaA/KAW45wJqXhz1zGTV6zVCbIlT8GpeTrm/dekdRuAN3iSEfGEwGpIAuOFnCbHaadpRLjztedMKMGD8dQuVsj+H+pl1W+LmylbHlOG00md0r52lL3THGEoftMXX6lz5wNHag1gK3HyS9IBvUJYoGksNbxeJTNsvr [TRUNCATED]
(dd007ab9-12ca-11e8-b201-8fec456d096a) Endpoint request body after transformations: {"resource":"/notes","path":"/notes","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":"TH","Content-Type":"application/json","Host":"binkm6jb4m.execute-api.us-east-2.amazonaws.com","User-Agent":"axios/0.17.1","Via":"1.1 2578d443f39536d43a9a2eccaa197f91.cloudfront.net (CloudFront)","X-Amz-Cf-Id":"M7sRK9ayuIl-I-RT8FGqtHCPSxOLSuKooj1F8U-KhamS25DR6lra0A==","x-amz-date":"20180216T033833Z","x-amz-security-token":"AgoGb3JpZ2luEKP//////////wEaCXVzLWVhc3QtMiKAAlTmYUda+bA65tBI6dCcB4aubUmGzAvAvBeZubcXXl/z0PWg5aoZ/G6FrFlfWcgKy9XxiB8wKvVaZDVbdULvE6NF0LoLIIstPS5wlthyEk8VSM3oYAGfqvQvZ9NW/NM0VzKeegM2zi0bQg10Az9XBdDzYIMGeMSbnE41dZ/T7kcPvs1veqGpBxHYA5+PooAInky7VgotOCv9FAvXwLoRQqN4R51jYYEcI+SDyg1y42MmD12xdB5RAc4rzfCZ9zSwDnWlyAHXDqBCuNb0FXlXUs051IyjCUzRliG5rXHz [TRUNCATED]
(dd007ab9-12ca-11e8-b201-8fec456d096a) Sending request to https://lambda.us-east-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-2:503179977678:function:notes-app-api-prod-create/invocations
(dd007ab9-12ca-11e8-b201-8fec456d096a) Received response. Integration latency: 115 ms
(dd007ab9-12ca-11e8-b201-8fec456d096a) Endpoint response body before transformations:
{
"statusCode": 500,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
},
"body": "{\"status\":false}"
}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Endpoint response headers: {X-Amz-Executed-Version=$LATEST, x-amzn-Remapped-Content-Length=0, Connection=keep-alive, x-amzn-RequestId=dd0499ca-12ca-11e8-b76e-b92f44150ead, Content-Length=132, Date=Fri, 16 Feb 2018 03:38:33 GMT, X-Amzn-Trace-Id=root=1-5a865239-7c7e925f212f79fb2c857beb;sampled=0, Content-Type=application/json}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method response body after transformations:
{
"status": false
}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method response headers: {Access-Control-Allow-Origin=*, Access-Control-Allow-Credentials=true, X-Amzn-Trace-Id=sampled=0;root=1-5a865239-7c7e925f212f79fb2c857beb}
(dd007ab9-12ca-11e8-b201-8fec456d096a) Successfully completed execution
(dd007ab9-12ca-11e8-b201-8fec456d096a) Method completed with status: 500
@ivanms1 Are these the Lambda logs? You should be able to see your console.log if you followed the steps in this chapter - https://serverless-stack.com/chapters/api-gateway-and-lambda-logs.html
@jayair ok I think I am finally getting somewhere here, after I realized I've been looking at the wrong logs.
This is the error I a getting on my create function.
2018-02-19T06:12:58.561Z ee074e14-153b-11e8-9638-d525c1b2a4e8 { ValidationException: One or more parameter values were invalid: Missing the key userId in the item
at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:48:27)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:685:12)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
message: 'One or more parameter values were invalid: Missing the key userId in the item',
code: 'ValidationException',
time: 2018-02-19T06:12:58.559Z,
requestId: '3LLKC80485R47TOBCVUR20IISFVV4KQNSO5AEMVJF66Q9ASUAAJG',
statusCode: 400,
retryable: false,
retryDelay: 18.56955639307114 }
I checked my create.js I corrected one typo, but I am still getting the same error.
Hi @jayair . I have the same problem that @ivanms1. API call test fail because userId is missing.
This is my API call test:
qazuor@NOSE4 /v/w/RevolAppBackend> apig-test \
--username='MYEMAIL' \
--password='MYPASS' \
--user-pool-id='us-east-1_n6A0s2ESX' \
--app-client-id='31n7jcfg8omah59vij29c6o0jr' \
--cognito-region='us-east-1' \
--identity-pool-id='us-east-1:c600aabf-ddf3-486d-a250-8bcfadde9779' \
--invoke-url='https://btoih37hxb.execute-api.us-east-1.amazonaws.com/prod' \
--api-gateway-region='us-east-1' \
--path-template='/events' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
I put a console logs in my function first to log the error:
2018-02-19 07:53:08.420 (-03:00) 119ce312-1563-11e8-9914-4d534293ef89 { ValidationException: One or more parameter values were invalid: Type mismatch for key userId expected: S actual: NULL
at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:48:27)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:685:12)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
message: 'One or more parameter values were invalid: Type mismatch for key userId expected: S actual: NULL',
code: 'ValidationException',
time: 2018-02-19T10:53:08.417Z,
requestId: 'TLFSSK6BAKV2MDU93008ROH2BFVV4KQNSO5AEMVJF66Q9ASUAAJG',
statusCode: 400,
retryable: false,
retryDelay: 34.34380403084148 }
And the to see what info have in event.requestContext:
requestContext: {
requestTime: '19/Feb/2018:10:38:42 +0000',
path: '/prod/events',
accountId: '751262903915',
protocol: 'HTTP/1.1',
resourceId: 'avzh5i',
stage: 'prod',
requestTimeEpoch: 1519036722589,
requestId: '0e03050e-1561-11e8-a372-c1ed968bbe7b',
identity: {
cognitoIdentityPoolId: null,
accountId: null,
cognitoIdentityId: null,
caller: null,
sourceIp: '181.93.216.110',
accessKey: null,
cognitoAuthenticationType: null,
cognitoAuthenticationProvider: null,
userArn: null,
userAgent: 'axios/0.17.1',
user: null
},
resourcePath: '/events',
httpMethod: 'POST',
apiId: 'btoih37hxb'
}
All cognito related info, into event.requestContext.identity is empty.
I google it for hours but, I cant found any solution.
This is my serverless.yml file:
service: revolapp
# Use serverless-webpack plugin to transpile ES6/ES7
plugins:
- serverless-webpack
# Enable auto-packing of external modules
custom:
webpackIncludeModules: true
provider:
name: aws
runtime: nodejs6.10
stage: prod
region: us-east-1
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-1:*:*"
functions:
create-event:
handler: services/events/create.main
events:
- http: post /events
cors: true
authorizer: aws_iam
get-event:
handler: services/events/get.main
events:
- http: get /events/{id}
cors: true
authorizer: aws_iam
update-event:
handler: services/events/update.main
events:
- http: put /events/{id}
cors: true
authorizer: aws_iam
delete-event:
handler: services/events/delete.main
events:
- http: delete /events/{id}
cors: true
authorizer: aws_iam
list-events:
handler: services/events/list.main
events:
- http: get /events
cors: true
authorizer: aws_iam
This my create.js file:
import uuid from "uuid";
import * as dynamoDbLib from "../../libs/dynamodb-lib";
import { success, failure } from "../../libs/response-lib";
export async function main(event, context, callback) {
const data = JSON.parse(event.body);
const params = {
TableName: "events",
Item: {
userId: event.requestContext.identity.cognitoIdentityId,
eventId: uuid.v1(),
content: data.content,
attachment: data.attachment,
createdAt: new Date().getTime()
}
};
console.log('event:', event);
try {
await dynamoDbLib.call("put", params);
callback(null, success(params.Item));
} catch (e) {
console.log(e);
callback(
null,
failure(
{
status: false
}
)
);
}
}
All the code is in https://github.com/qazuor/RevolAppBackend
Please help me.
Sorry for my not so good English
@ivanms1 This error is basically saying that the userId is not being passed in. So the best thing would be to console.log what the userId is and see what you are passing in.
@qazuor The serverless.yml in your project is not formatted properly. This is a very annoying issue that most people run into.
Your create looks like this:
create-event:
handler: services/events/create.main
events:
- http: post /events
cors: true
authorizer: aws_iam
Versus what it should look like
create:
handler: create.main
events:
- http:
path: notes
method: post
cors: true
authorizer: aws_iam
The issue is that your functions are not using an authorizer (are public), so there is no Cognito Identity Id.
Hi @jayair, first thanks very much for this tutorials, It has been precious!
I am running into this IAM role error when testing the api with apig-test.
Authenticating with User Pool
Getting temporary credentials
Invalid identity pool configuration. Check assigned IAM roles for this pool.
The message is very obvious, I have checked multiple times my IAM roles from the identity pool as well as the policy statement and the relationship with the user pool. But hard to debug the origin of the error...
If this is a common error, it would be grateful if you have a hint to fix this.
Thanks !
@adoolaeghe Yeah these are super annoying to deal with. In this chapter - https://serverless-stack.com/chapters/debugging-serverless-api-issues.html, we talk about using the Policy Simulator to help you debug it. Give it a try and let me know how it goes.
@jayair Thank for your response.
I followed the policy simulator and my policy role does return an Accepted response.
In doubt of the wrong setup, I re-followed the steps with a different AWS account, and I am still getting the same error at the end, which is getting very curious...
Just checking in on this, which I've just encountered:
Unable to import module 'create': Error
at Function.Module._resolveFilename (module.js:469:15)
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:1:1474)
at n (/var/task/create.js:1:220)
at Object.<anonymous> (/var/task/create.js:1:1659)
at n (/var/task/create.js:1:220)
at /var/task/create.js:1:641
at Object.<anonymous> (/var/task/create.js:1:651)
I see that the previous solution was to revert to serverless 1.17.0 - I'm on 1.26.0 - is the solution really to roll all the way back to .17??
Perhaps it's time to consider an entirely different approach if serverless and webpack just aren't going to play nicely? Perhaps I'm misreading the actual issue involved?
Seconding @brianmade I am on Serverless 1.26.0 and experiencing the same issues as @tsdorsey originally posted last year - rolling back to 1.17.0 doesn't seem like a solution, more a temporary fix.
Has anyone else succeeded in getting later versions of Serverless to play nicely with Babel and Webpack?
This is probably not the best way to accomplish this in the long term, but after reading serverless-webpack's guide on forced-inclusion I have edited my serverless.yml as follows to force the inclusion of babel-runtime:
Previously it was:
custom:
webpackIncludeModules: true
Which packaged as:
Entrypoint calculators = calculators.js
Entrypoint handler = handler.js
[0] external "babel-runtime/core-js/json/stringify" 42 bytes {0} {1} [built]
[1] ./handler.js 1020 bytes {0} [built]
[2] ./libs/response-lib.js 721 bytes {1} [built]
[3] ./calculators.js 1.98 KiB {1} [built]
Serverless: No external modules needed
Then errorred as:
Thu Mar 01 12:25:28 UTC 2018 : Endpoint response body before transformations: {"errorMessage":"Cannot find module 'babel-runtime/core-js/json/stringify'","errorType":"Error","stackTrace":["Function.Module._load (module.js:417:25)","Module.require (module.js:497:17)","require (internal/module.js:20:19)","Object.defineProperty.value (/var/task/calculators.js:1:676)","n (/var/task/calculators.js:1:220)","Object.<anonymous> (/var/task/calculators.js:1:1159)","n (/var/task/calculators.js:1:220)","/var/task/calculators.js:1:641","Object.<anonymous> (/var/task/calculators.js:1:650)"]}
Following the webpack guidance on forcing includes:
custom:
webpackIncludeModules:
forceInclude:
- babel-runtime
Which packages as:
Entrypoint calculators = calculators.js
Entrypoint handler = handler.js
[0] external "babel-runtime/core-js/json/stringify" 42 bytes {0} {1} [built]
[1] ./handler.js 1020 bytes {0} [built]
[2] ./libs/response-lib.js 721 bytes {1} [built]
[3] ./calculators.js 1.98 KiB {1} [built]
Serverless: Package lock found - Using locked versions
Serverless: Packing external modules: babel-runtime@^6.26.0
@rgandco I'm on 1.26.0 and it's working just fine. I don't pretend to know which switch you need to flip to get this to work but I can show you a very boiled down project I just published showing how I'm using cross stack references which uses webpack and babel to do just what you're trying to do.
Head over to
https://github.com/tsdorsey/myMultiStackResources or
https://github.com/tsdorsey/myMultiStackApi
(doesn't matter which)
Look at the following files: .babelrc and webpack.config.js These files will be identical in both repos. Also look at serverless.yml
My gut says you need the transform-runtime babel plugin.
I have stood on the shoulders of others to put those files together but I know they work to include the babel-runtime elements that are needed.
@tsdorsey I've mirrored your .babelrc and webpack.config.js to the letter. I've aligned your serverless.yml with mine for all the relevant areas of configuration.
Still doesn't package babel-runtime or any other external modules, still generates the same error when run within Lambda (but not locally as the modules exist).
Could it be an OS specific issue? I'm deploying from a Windows 10 laptop shrug. Clutching at straws.
@rgandco I Didn't think it would matter but I tried moving the babel-runtime into devDependencies but it still works for me.
I'm on macOS 10.12.6
Could you clone the Resources repo (the API one requires the Resources stack to be deployed) and run
yarn install then
./sls package --verbose
I get:
Serverless: Removing [redacted]/resources/.webpack
Serverless: Using multi-compile (individual packaging)
Serverless: Bundling with Webpack...
Time: 692ms
Asset Size Chunks Chunk Names
src/handlers/cognito.js 3.36 kB 0 [emitted] src/handlers/cognito
[0] ./src/handlers/cognito.js 707 bytes {0} [built]
[1] external "babel-runtime/helpers/asyncToGenerator" 42 bytes {0} [not cacheable]
Serverless: Fetch dependency graph from [redacted]/resources/package.json
Serverless: Packing external modules: [email protected]
Serverless: Package took [2504 ms]
Serverless: Copy modules: [redacted]/resources/.webpack/cognitoAutoConfirm [651 ms]
Serverless: Prune: [redacted]/resources/.webpack/cognitoAutoConfirm [577 ms]
Serverless: Zip function: [redacted]/resources/.webpack/cognitoAutoConfirm [1008 ms]
Serverless: Packaging service...
Serverless: Remove [redacted]/resources/.webpack
I am unable to get this test to pass.
I get the following error:
{ status: 502,
statusText: 'Bad Gateway',
data: { message: 'Internal server error' }
When I looked further into what might be going on, I realized that my Lambda function for create is not working. When I run the test in the AWS console for the function, I get the following error:
{
"errorMessage": "Cannot find module 'babel-runtime/regenerator'",
"errorType": "Error",
"stackTrace": [
"Module.require (module.js:497:17)",
"require (internal/module.js:20:19)",
"Object.<anonymous> (/var/task/create.js:1:1474)",
"n (/var/task/create.js:1:220)",
"Object.<anonymous> (/var/task/create.js:1:1659)",
"n (/var/task/create.js:1:220)",
"/var/task/create.js:1:641",
"Object.<anonymous> (/var/task/create.js:1:651)"
]
}
I am on the latest versions of both Serverless and NPM and am truly stumped.
@rgandco - the force include solution worked for me ... thank you so much!
@tsdorsey Short update. Cloned your repo and followed your instructions and it works exactly as expected, my day is a bit all over the place today but I'm going to do a comparison of my project and yours and then report back.
@tsdorsey The only differences I can really see are:
versionFunctions set to falseendpointType set to REGIONAL(Removing these made no difference)
sls script that sets some environment variables, and I don't - which might be why I'm getting the following warning on my package: Asset Size Chunks Chunk Names
users.js 1.65 KiB 0 [emitted] users
Entrypoint users = users.js
[0] ./config.js 208 bytes {0} [built]
[1] external "amazon-cognito-identity-js" 42 bytes {0} [built]
[2] external "babel-runtime/core-js/json/stringify" 42 bytes {0} [built]
[3] ./libs/response-lib.js 721 bytes {0} [built]
[4] external "babel-runtime/core-js/promise" 42 bytes {0} [built]
[5] ./users.js 1.36 KiB {0} [built]
WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.
Serverless: Fetch dependency graph from [redacted]\package.json
Serverless: No external modules needed
@tsdorsey Actually - I'm using a different version of webpack too - I'm on ^4.3.0 and you're on 3.11.0
@tsdorsey I've downgraded webpack to 3.11.0 to match you. Working perfectly now!
@tzlukoma Suggest you follow along - ditch the work around I used above.
Anyone have any ideas why more recent versions of webpack are struggling?
Hey all, no idea where to turn at this point. I'm getting a 'Bad Gateway' status: 502 error when I try a post test. Anyone solve for this issue. Here's my serverless.yml
service: notes-app-api
plugins:
- serverless-webpack
custom:
webpackIncludeModules: true
provider:
name: aws
runtime: nodejs6.10
stage: prod
region: us-east-2
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-2:*:*"
functions:
create:
handler: create.main
events:
- http:
path: notes
method: post
cors: true
authorizer: aws_iam
Here is my attempt
$ apig-test --username='[email protected]' --password='Passw0rd!' --user-pool-id='us-east-2_NJOBuJBTc' --app-client-id='fuuqc1df2ka7lloks5l7pnXXX' --cognito-region='us-east-2' --identity-pool-id='us-east-2:27900e23-86db-4626-bbd0-7fe70108XXXX' --invoke-url='https://v569bcxh1h.execute-api.us-east-2.amazonaws.com/prod' --api-gateway-region='us-east-2' --path-template='/notes' --method='POST' --body='{"content":"hello pluto","attachment":"hello.jpg"}'
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 502,
statusText: 'Bad Gateway',
data: { message: 'Internal server error' } }
API Deploy
Service Information
service: notes-app-api
stage: prod
region: us-east-2
api keys: None
endpoints:
POST - https://v569bcxh1h.execute-api.us-east-2.amazonaws.com/prod/notes
GET - https://v569bcxh1h.execute-api.us-east-2.amazonaws.com/prod/notes/{id}
GET - https://v569bcxh1h.execute-api.us-east-2.amazonaws.com/prod/notes
PUT - https://v569bcxh1h.execute-api.us-east-2.amazonaws.com/prod/notes/{id}
DELETE - https://v569bcxh1h.execute-api.us-east-2.amazonaws.com/prod/notes/{id}
functions:
create: notes-app-api-prod-create
get: notes-app-api-prod-get
list: notes-app-api-prod-list
update: notes-app-api-prod-update
delete: notes-app-api-prod-delete
@F-Adam-B have you read through some of the other discussions on this issue? Searching for 502 on this page yields several threads. Do you see anything in the cloudwatch logs?
@tsdorsey I have and had no such luck. The logs are similar to what you were experiencing
Unable to import module 'create': Error
at Function.Module._resolveFilename (module.js:469:15)
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:1:1474)
at n (/var/task/create.js:1:220)
at Object.<anonymous> (/var/task/create.js:1:1659)
at n (/var/task/create.js:1:220)
at /var/task/create.js:1:641
at Object.<anonymous> (/var/task/create.js:1:651)
I've rolled back serverless and also confirmed my dynamodb-lib.js shows the correct region. Here's my package.json just in case there's anything I missed.
{
"name": "notes-app-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"aws-sdk": "^2.205.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.3",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-3": "^6.24.1",
"serverless-webpack": "^4.4.0",
"webpack": "^3.11.0",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"babel-runtime": "^6.26.0",
"uuid": "^3.2.1"
}
}
@rgandco and @tsdorsey solution nailed it for me. You guys rock. This is the current problem and should be addressed in the tutorial. Install Webpack @ 3.11.0 instead of the most current version and you won't rabbit-hole for days on end trying to figure out the problem.
To do this just change your package.json webpack line to look like this:
"webpack": "^3.11.0",
and then run:
npm install
re-run your deploy and test it out!
i have the same issue "Unable to import module 'create': Error at Function.Module._resolveFilename...". After reverting serverless to version 1.17.0 and add the following code to serverless.yml, it works.
custom:
webpackIncludeModules:
forceInclude:
- babel-runtime
I hope we don't need to revert back to 1.17.0.
@brianmade So the issue for the newer web pack version? I'll add a note to force that version until we find a fix for the newer version.
@hollygood Can you compare your package.json to https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/package.json and try the older version of webpack instead?
FYI, if anyone is still struggling with getting the apig-test command to run in Windows, it won't work in PowerShell as written (with \ as the escape character for the body's json), but it does work using a plain 'ol cmd window. (I did it successfully running cmd as admin, but didn't try it otherwise).
I've been out of the windows ecosystem for while, but I did this tutorial on my personal Surface... I'm already having flashbacks of yak shaving in PowerShell in a previous life.
P.S.: This is specifically addressing the problem described here: https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-316801852
@jrnail23 Thanks for this. Our windows tips are pretty spotty. So this should help if anybody is running into similar issues.
Hi I'm a little stuck with a 401 error:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 401,
statusText: 'Unauthorized',
data: { message: 'Unauthorized' } }
Has any one had anything like this? And advice on how to resolve it?
@sabrown84 Hmm. It looks like it authenticated fine but it failed to make the request. You can try following the steps in this chapter to debug it - https://serverless-stack.com/chapters/debugging-serverless-api-issues.html. Specifically, use the Policy Simulator to check if you have the permissions set up correctly.
any one faced to this problem befor? @jayair
$ apig-test --username [email protected] --password Passw0rd! --user-pool-id eu-west-1_********
--app-client-id ****** --cognito-region eu-west-1 --identity-pool-id eu-west-1:+++++-+++++-+++++-b826-5a7742dba847 --invoke-url https://******.execute-api.eu-west-1.amazonaws.com/dev/ --api-getway-region eu-west-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: 'Credential should be scoped to a valid region, not \'us-east-1\'. ' } }
@Dorostkar I think this has to do with your ~/.aws/credentials. What does that file look like for you?
At everyone here: Can you check and confirm, that the only difference between using Webpack 3 and Webpack 4 is a different log in the Webpack compile output like:
[2] external "babel-runtime/core-js/json/stringify" 42 bytes {0} [built] in v4 vs. [2] external "babel-runtime" 42 bytes {0} [built] in v3?
Please test that with SLS 1.25 or 1.26.1 (should not matter) and serverless-webpack 5.1.0.
If that's the case it is a bug in serverless-webpack in combination with Webpack 4 and I'll provide a bugfix release asap. Thank you.
BTW: Do you have a sample project somewhere where the issue is reproducible when switching webpack versions?
@HyperBrain Thanks for checking in. I haven't confirmed it yet, but here is a link to the repo with Webpack 3 - https://github.com/AnomalyInnovations/serverless-stack-demo-api
@jayair Thanks. I'll grab that and do some tests to see if I can find something.
What was the resolution to this error? I'm getting the same thing.
apig-test --username [email protected] --password Passw0rd! --user-pool-id us-east-1_HwIVtcRh2 --app-client-id 34bb7b87t6rtc387foiletrldf --cognito-region us-east-1 --identity-pool-id us-east-1:285f61b7-8a95-4596-90ce-7f7e1848c2ed --invoke-url https://6xosj8ww6h.execute-api.us-east-1.amazonaws.com/prod/words --api-gateway-region us-east-1' --path-template /words' --method POST --body {"content":"hello world","attachment":"hello.jpg"}
Authenticating with User Pool
Getting temporary credentials
Making API request
C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:31
throw err;
^
SyntaxError: Unexpected token c in JSON at position 1
at JSON.parse (<anonymous>)
at makeRequest (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:131:19)
at C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\index.js:114:5
at C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials.js:123:23
at Response.<anonymous> (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials\cognito_identity_credentials.js:258:7)
at Request.<anonymous> (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:364:18)
at Request.callListeners (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\sequential_executor.js:105:20)
at Request.emit (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\sequential_executor.js:77:10)
at Request.emit (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:683:14)
at Request.transition (C:\Users\proet\AppData\Roaming\npm\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\request.js:22:10)
I run apig-test as below:
apig-test --username='[email protected]' --password='Passw0rd!' --user-pool-id='ap-southeast-1_XXXXXXXXX' --app-client-id='xxxxxxxxxxx' --cognito-region='ap-southeast-1' --identity-pool-id='xxxxxxxxxx' --invoke-url='https://xxxxxxx.execute-api.ap-southeast-1.amazonaws.com/prod' --api-gateway-region='ap-southeast-1' --path-template='/notes' --method='POST' --body='{"content":"hello world","attachment":"hello.jpg"}'
Note that I have masked my specific information above, which I have double checked.
I get the following error when I run apig-test:
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
Any pointers?
Checking the logs from Cloudwatch, I see the following under the create API log:
{ AccessDeniedException: User: arn:aws:sts::************:assumed-role/notes-app-api-prod-ap-southeast-1-lambdaRole/notes-app-api-prod-create is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:ap-southeast-1:***************:table/notes
Strangely, I get the server error every time I run apig-test, but it is not logged every time. I'm on the free tier, I suppose this could be due to some limits? Can anyone suggest how I can check this?
I had to add DynamoDB read/write access for the prod-notes-app-api-lambda role. I used the IAM Policy Simulator to check/add this.
I am not sure if I missed it in some step of the tutorial. I do have the iamRoleStatements set up to allow this in the serverless.yml file.
@asayyad I'm not sure what's causing your specific issue but the resolution for some of the issues above are reverting to Webpack 3. Here is the one we use in the tutorial - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/package.json#L28
@karthickng These are the IAM statements that give this permission - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/serverless.yml#L19
Just check to make sure you have these and they are indented exactly like the ones in the tutorial.
@jayair I updated the project to Webpack 4 + serverless-webpack 5.1.0. The call of notes/GET returns now Endpoint response body before transformations: {"statusCode":500,"headers":{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":true},"body":"{\"status\":false}"} which is correct because I did not create the notes table.
But the require failed error is not there, so I'm sure that my upgrade to webpack 4 worked. The only thing I had to update too was the babel loader (to 7.1.3) because it is the first version to support Webpack 4 and some configuration parts.
I will open a PR now (will reference it here) for testing. If it works for you too, please let me know.
Here you go.
@HyperBrain Thanks!
@HyperBrain @jayair Thanks both for this, though having tried this in a brand new project, I am getting a bizarre outcome - webpack builds the example fine but then doesn't execute the function (if I run sls invoke local --function foo). Just me seeing this?
@rgandco What do you see in the console? Maybe you need to supply a payload to the function (using the --path=...path-to-some-event.json...)
@HyperBrain Nothing after the webpack build - it doesn't terminate, but it doesn't run the function either.
@HyperBrain @jayair False alarm. I was running the commands from MINGW64 as I happened to have a terminal open rather than just from standard cmd on W10. Apparently sls does not like this...
@rgandco Good to know. I use Git bash on Windows 10 which works perfectly.
@HyperBrain MINGW64 is Git bash... I'd love to know how yours is working and mine is stalling!
I actually have no idea why it works for me...
$ uname
MINGW64_NT-10.0
$ uname -r
2.10.0(0.325/5/3)
$ git --version
git version 2.16.2.windows.1
Then I have nvm for Windows installed, with all Node versions installed and working (4.x, 6.x, 8.x, 9.x). I installed everything (nvm install xxx and npm install stuff) from within MINGW64 and not from PowerShell. Is your problem restricted to invoke local, or doesn't Serverless work at all?
I'm also seeing the "Unable to import module 'create': Error" issue.
This thread seems to be about several unrelated issues and I might be getting the various solutions mixed-up, but I tried various versions of webpack (3.11.0, 4.4.1, 4.2.0) with no luck.
@AGanguli With webpack 4 you should check if you have all necessary configuration options set (the ones that my PR #12 properly changed). The error message itself means that one node module that is expected to be packaged is actually missing in the ZIP package. Which one is not easy to tell because the lambda will exit even before your code is executed.
I also agree that this issue is a wild mixture of different problems. Maybe a solution would be that you open an issue directly in serverless-webpack and we can discuss and solve the configuration there, so that anyone stumbling onto it again will find a solution (at least for one variant of the issue). In my repo there were already some of them (for specific modules that needed special treatment).
@HyperBrain Based on that, shouldn't it be possible to brute-force this temporarily by putting all the devDependencies in dependencies? (I tried it, and it didn't work. But curious why not.)
serverless-webpack does an optimized packaging and replaces the Serverless' one.
What you can try to do is, to use custom: webpack: includeModules: forceInclude: and set it to an array of package names that are forcefully included into the zip file. However, I don't remember if I automatically excluded the dev dependencies from forced inclusion, but it should be worth a try.
... or just move deps from dev to prod until it works to isolate the one that is missing
Success. Thanks! Actually, I'm getting an access denied exception, but that's something I know how to debug.
I'll fix that and then back out my hack gradually so I can see which module did the trick.
This stanza in serverless.yml appears to be what makes it work:
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules:
forceInclude:
- serverless-webpack
Stange. You should never ever have a runtime dependency to sls-webpack
AGanguli notifications@github.com schrieb am Do., 29. März 2018, 9:49
nachm.:
This stanza in serverless.yml appears to be what makes it work:
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules:
forceInclude:
- serverless-webpack—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/AnomalyInnovations/serverless-stack-com/issues/112#issuecomment-377351674,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AFRM3hs0JpJR5997GXBRJiLLtsRw9Z0mks5tjTrOgaJpZM4OdNcs
.
I was getting the same Unexpected token error as Asayyad above trying to run Apig-test in the Windows 10 Powershell. I switched to the CMD.exe terminal and it worked. Sort of ,...I got a different error at that point which was " _status: 400,
statusText: 'Bad Request',_
I then tried running the command in the Bash terminal in VS Code and it gave me a much more specific error "_getaddrinfo ENOTFOUND hhh-notes-app.auth.us-east-2.amazoncognito.comc hro-notes-app.auth.us-east-2.amazoncognito.comc:443"_
Ended up that I used the wrong URL which should have been https://lfd3453976k.execute-api.us-east-2.amazonaws.com/prod
Moral of my story - If first you don't succeed in one terminal, try another. Especially if you are using Windows. And Bash seems to have the best error reporting.
@viccooper142 Thanks for reporting back!
How does the APIclass in Amplify pass similar info as in the apig-test below? How does my API know whether the cognito user who invoked the API belongs to identity pool in which I attached :
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:YOUR_API_GATEWAY_REGION:*:YOUR_API_GATEWAY_ID/*"
]
}
apig-test \
--username='[email protected]' \
--password='Passw0rd!' \
--user-pool-id='us-east-1_YBhdXYvix' \
--app-client-id='29qwoeorti0ctjkur5h91lkw5g' \
--cognito-region='us-east-1' \
--identity-pool-id='us-east-1:565cc505-5486-4278-bf0f-9736p9apq8m5' \
--invoke-url='https://w5z1hluqmp5.execute-api.us-east-1.amazonaws.com/test' \
--api-gateway-region='us-east-1' \
--path-template='/notes' \
--method='POST' \
--body='{"content":"hello world","attachment":"hello.jpg"}'
@Tee88 Amplify handles your app as a whole. When you first configure Amplify we set all the Cognito info, similar to what we do for apig-test - https://github.com/AnomalyInnovations/serverless-stack-demo-client/blob/master/src/config.js
So it knows that you are using those credentials to access the API.
Greetings. Having an issue currently. From what i can gather it may be babel related, though i have followed the instructions exactly, and have not had any errors up until now that were easily fixed typos.
Getting the 502 error:
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 502,
statusText: 'Bad Gateway',
data: { message: 'Internal server error' } }
Cloudwatch output:
Syntax error in module 'create': SyntaxError
async function main(event, context, callback) {
^^^^^^^^
SyntaxError: Unexpected token function
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
Appreciate the help. This body of work is incredible.
BB
EDIT
Changing my Lambda function runtime to Node 8.10 in the AWS Console eliminated the error. I would still like to better understand the issue, but i can move forward
EDIT AGAIN
Looks like I was bitten by an upstream change. The commit from 1.5 days ago added support for Node8.10. I just happen to be working through it when it happened. Please disregard. I've rebuilt all files.
@willieray25 Yeah there was a recent update that can cause this. Glad you figure it out.
@jayair : I'm not able to get past the following error. My .aws/credentials file has the access key and secret key and the region is hard coded into the dynamo-lib file. Do you happen to know what could cause this ? The region on all my js files / user pools / etc are all 'us-west-2' ...
{
status: 403,
statusText: 'Forbidden',
data: { message: 'Credential should be scoped to a valid region, not \'us-east-1\'. ' }
}
@thevamad This usually happens when the region used to sign the requests doesn't match the endpoint. Can I see the full command that is causing this error?
I'm running this on a windows machine and had to do an additional step to set up serverless config params (for some reason aws configure was working to run CLI commands but not working with the serverless code)..
npx aws-api-gateway-cli-test --username [email protected] --p
assword Password_1 --user-pool-id us-west-2_KkiPPu5xj --app-client-id ohorcp7n9q
tap2jqbrmnof789 --cognito-region us-west-2 --identity-pool-id us-west-2:e5f17dcd
-2650-4f22-a3e4-d19531195986 --invoke-url https://q350s3y4r3.execute-api.us-west
-2.amazonaws.com/prod/notes --api-gateway -region us-west-2 --path-template note
s --method POST --body "{""content"":""helloworld"",""attachment"":""hello.jpg""
}"
@thevamad I'm not sure if this is a typo --api-gateway -region but just make sure the region is set correctly.
Oh man. You're right. That was a typo :) Thanks a ton!
This solved my 403:
IAM -> Roles -> Cognito_notesAuth_Role -> oneClick_Cognito_notesAuth_Role_XXXXXXXXX -> Edit Policy -> JSON:
On line 30, the copy/paste of the code from the tutorial had beed "auto-corrected" from "arn", to "Arn".
It should be lowercase.
@jonasbarsten Oh wow, that is a really annoying problem caused by auto-correct.
@jayair Not as annoying as the world was before you made this tutorial ;)
I'm getting
~/notes-app-api master scripts/aws-api-gateway-cli-test.sh
npx: installed 103 in 5.486s
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 500,
statusText: 'Internal Server Error',
data: { status: false } }
When I run the test. I've added console.log(e) to all the handlers, but don't get any additional information. Where should I look to find my mistake? https://github.com/ahammond/notes-app-api is my WIP.
Hmm. serverless --aws-profile personal logs -f create gives me
START RequestId: 220ccc23-4e59-11e8-ac2d-1f262356d857 Version: $LATEST
2018-05-02 15:35:37.700 (-07:00) 220ccc23-4e59-11e8-ac2d-1f262356d857 { CredentialsError: Missing credentials in config
at Object.fs.openSync (fs.js:646:18)
at Object.fs.readFileSync (fs.js:551: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:94: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:332:24)
at Config.getCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:352:9)
at Request.VALIDATE_CREDENTIALS (/var/runtime/node_modules/aws-sdk/lib/event_listeners.js:80:26)
message: 'Missing credentials in config',
errno: -2,
code: 'CredentialsError',
syscall: 'open',
path: '/home/sbx_user1059/.aws/credentials',
time: 2018-05-02T22:35:37.692Z,
originalError:
{ message: 'Could not load credentials from SharedIniFileCredentials',
errno: -2,
code: 'CredentialsError',
syscall: 'open',
path: '/home/sbx_user1059/.aws/credentials',
time: 2018-05-02T22:35:37.692Z,
originalError:
{ errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/home/sbx_user1059/.aws/credentials',
message: 'ENOENT: no such file or directory, open \'/home/sbx_user1059/.aws/credentials\'' } } }
END RequestId: 220ccc23-4e59-11e8-ac2d-1f262356d857
REPORT RequestId: 220ccc23-4e59-11e8-ac2d-1f262356d857 Duration: 37.66 ms Billed Duration: 100 ms Memory Size: 1024 MB Max Memory Used: 63 MB
I have multiple aws profiles. Related?
@ahammond : I had the same issue. I used this command to configure the serverless credentials per the following link. I had previously set this up using aws configure which only seemed to use the credentials on any CLI command that was run.
https://serverless.com/framework/docs/providers/aws/guide/credentials/
serverless config credentials --provider aws --key AKIAIOSFODNN7EXAMPLE --secret wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
@thevamad I tried that (clobbered my default profile with my personal profile) and am still getting the same error.
@ahammond Are you setting which profile to use in your Lambda function?
@ahammond : the other thing that worked for me is setting credentials in the lambda like so
AWS.Config.update ( {accessKeyId: 'AKID',
secretAccessKey: 'SECRET',
region: 'us-west-2'});
I also received a 403 - Forbidden access.
After doublechecking erverything, it turns out, that the cut'n'paste of the Access Rule from the PDF was the problem. The hyphen characters from the longer lines are not copied and so the keywords are rubbish. You can try it by yourself. Just copy the snippet from the PDF and insert it into your editor.
"Resource": [
"arn:aws:s3:::YOUR_S3_UPLOADS_BUCKET_NAME/private/${cognitoidentity.
amazonaws.com:sub}/*"
:
:
must be
"Resource": [
"arn:aws:s3:::YOUR_S3_UPLOADS_BUCKET_NAME/private/${cognito-identity.
amazonaws.com:sub}/*"
:
:
and as well
"Resource": [
"arn:aws:executeapi:
YOUR_API_GATEWAY_REGION::YOUR_API_GATEWAY_ID/"
]
must be
"Resource": [
"arn:aws:execute-api:
YOUR_API_GATEWAY_REGION::YOUR_API_GATEWAY_ID/"
]
I'm not sure if it is a mac specific copy'n'paste issue, but it takes me hours to figure out whats going wrong. Maybe this hint is helpful ....
@devsteff Hmmm that's weird. I just tried the exact same lines from the PDF and it worked okay for me. I'm on macOS 10.13. Are the hyphens missing only for these snippets?
Yes, Seems so. I figured out, that when using the Apple Preview App for the PDF, copy'n'paste is ok. The hyphen is there, but line ist splittet and must be joined. But with Adobe Acrobat Reader App (Architecture: x86_64, Build: 18.11.20038.267465, AGM: 4.30.74, CoolType: 5.14.5, JP2K: 1.2.2.39492)
you can reproduce the issue. So I think it's more a Adobe twist, than a problem in the PDF.
@devsteff I see. Thanks for letting us know. I'll add a note in there.
This issue was moved to https://discourse.serverless-stack.com/t/comments-test-the-apis/122
@Ashraf-Younis-NM Can you post this here - https://discourse.serverless-stack.com/t/comments-test-the-apis/122? We are moving any discussions around the chapters to Discourse.
@jayair I'm running into the same problem as @mikhaelbendavid with error message. Checked all configurations all same as the tutorial. I was wondering what could be the problem? Many thanks!
@KatieChen1001 I replied in the Discourse thread.
I keep getting the 403 error but I'm not sure why. I've tried all the debugging suggestions, and even tried changing the policies around in the IAM (which arent giving me any denied errors). Here is what I'm finding in my logs
`npx aws-api-gateway-cli-test
--username='[email protected]'
--password='Passw0rd!'
--user-pool-id='us-east-2_95w6Kuh38'
--app-client-id='73shgtmv0jap1bem97iht8scqn'
--cognito-region='us-east-2'
--identity-pool-id='us-east-2:52d98313-948d-4cca-993a-feb52498bfc3'
--invoke-url='https://czojib8dpe.execute-api.us-east-2.amazonaws.com/prod'
--api-gateway-region='us-east-2'
--path-template=‘/todo’
--method='POST'
--body='{"content":"hello world","attachment":"hello.jpg"}'
npx: installed 106 in 4.168s
Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 403,
statusText: 'Forbidden',
data: { message: 'Forbidden' } } `
Something that I came across while testing in Windows is
NOTE. Most of the time the issue will be resolved by 1, 2, and 3 point. You only need to take care of mobilehub cognito identity pool id, if in your code you are using congintoIdentity from the event. As this will lead to some inconsistencies during testing, and you have to be more careful.
So, I successfully tested my command as given below
apig-test --username [email protected] --password Passw0rd! --user-pool-id us-east-1_YBhdXYvix --app-client-id 29qwoeorti0ctjkur5h91lkw5g --cognito-region us-east-1 --identity-pool-id us-east-1:565cc505-5486-4278-bf0f-9736p9apq8m5 --invoke-url https://w5z1hluqmp5.execute-api.us-east-1.amazonaws.com/test --api-gateway-region us-east-1 --path-template /notes --method POST --body {"content":"hello world","attachment":"hello.jpg"}
@marshallbunch Here is a sample one that I was using. I altered some of the values around but the format should be like so.
apig-test \ --username='[email protected]' \ --password='Passw0rd!' \ --user-pool-id='us-east-1_YBhdXYvix' \ --app-client-id='29qwoeorti0ctjkur5h91lkw5g' \ --cognito-region='us-east-1' \ --identity-pool-id='us-east-1:565cc505-5486-4278-bf0f-9736p9apq8m5' \ --invoke-url='https://w5z1hluqmp5.execute-api.us-east-1.amazonaws.com/test' \ --api-gateway-region='us-east-1' \ --path-template='/notes' \ --method='POST' \ --body='{"content":"hello world","attachment":"hello.jpg"}'
Is this thread still being supported? I don't want to thoroughly describe my issue if no one is able to assist! Cheers.
Post over on the forums instead — https://discourse.serverless-stack.com
I am not sure if this thread is still maintained or not, but I just wanted to thank @bradodarb for his comment on solving 403 error. After following his advice I was able to solve error.
Solution: keep --path-template empty and append your path value to the Gateway URL itself.
And also, Thanks to @jayair for such an amazing tutorial. You really are helping every tech enthusiast in the best possible way. Cheers !
@mgonawala Thanks for kind words!
Yeah we've moved over to our forums for chapter related comments.
I'm really stuck here, been at it 3 days so far. Here is the forum post: https://discourse.serverless-stack.com/t/debugging-api-gateway/2011/3 - posting here in case anyone can help?
I am on windows at stuck at this error, can anyone shed some light
{
status: 400,
statusText: 'Bad Request',
data: '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n' +
'<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">\n' +
'<TITLE>ERROR: The request could not be satisfied</TITLE>\n' +
'</HEAD><BODY>\n' +
'<H1>400 ERROR</H1>\n' +
'<H2>The request could not be satisfied.</H2>\n' +
'<HR noshade size="1px">\n' +
'Bad request.\n' +
"We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.\n" +
'<BR clear="all">\n' +
'If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.\n' +
'<BR clear="all">\n' +
'<HR noshade size="1px">\n' +
'<PRE>\n' +
'Generated by cloudfront (CloudFront)\n' +
'Request ID: ioI1VugXiqUDpE2XOUpgzpdFqLqOmIMJiwEuGdStUzb4pTMbgDldOQ==\n' +
'</PRE>\n' +
'<ADDRESS>\n' +
'</ADDRESS>\n' +
'</BODY></HTML>'
}
Can you post this over on — https://discourse.serverless-stack.com/
Hello everyone I am having a problem with testing the api. When I run all the other tests in mock, my backend is updated and I see what I created,updated,deleted,etc. But when I run the command(I'm omitting alot of details. 'body' is my main question here): npx aws-api-gateway-cli-test --api-gateway-region us-east-1 --path-template /requests --method POST --body "{\"content\":\"test req\",\"amount\":\"120\",\"attachment\":\"bye.jpg\"}"
its giving me this error:
Authenticating with User Pool
Getting temporary credentials
Making API request
undefined:1
{\
^
SyntaxError: Unexpected token \ in JSON at position 1
at JSON.parse (<anonymous>)
at makeRequest (C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\index.js:179:17)
at C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\index.js:152:5
at C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials.js:124:23
at C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials.js:212:15
at processTicksAndRejections (internal/process/task_queues.js:79:11)
I'm not too sure what I'm doing wrong. I'm trying to fix the syntax error but I'm extremely stuck :(
Can I get some help please. I'm on Windows 10!
@awahmed, looks like you have a before "content" that doesn't belong there :)
@jonasbarsten That's so wierd, I removed that and it gave me a very similar error at the same exact spot too. I just wanted to mention I am using powershell for this. Because I brought up Command Prompt and put my original command and that ended up working!
@awahmed did you get to a solution for your error.? I am also getting same error and cannot go pass it. Your help would be highly appreciated.
@agam-mishra I used Command prompt isntead of Powershell and ran the same command and it ended up working for me. For some reason Powershell was giving me that error only. Hope that helps
Hello everyone I am having a problem with testing the api. When I run all the other tests in mock, my backend is updated and I see what I created,updated,deleted,etc. But when I run the command(I'm omitting alot of details. 'body' is my main question here):
npx aws-api-gateway-cli-test --api-gateway-region us-east-1 --path-template /requests --method POST --body "{\"content\":\"test req\",\"amount\":\"120\",\"attachment\":\"bye.jpg\"}"its giving me this error:
Authenticating with User Pool Getting temporary credentials Making API request undefined:1 {\ ^ SyntaxError: Unexpected token \ in JSON at position 1 at JSON.parse (<anonymous>) at makeRequest (C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\index.js:179:17) at C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\index.js:152:5 at C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials.js:124:23 at C:\Users\aamai\AppData\Roaming\npm-cache\_npx\18348\node_modules\aws-api-gateway-cli-test\node_modules\aws-sdk\lib\credentials.js:212:15 at processTicksAndRejections (internal/process/task_queues.js:79:11)I'm not too sure what I'm doing wrong. I'm trying to fix the syntax error but I'm extremely stuck :(
Can I get some help please. I'm on Windows 10!
Hi @awahmed I'm getting the same error now. Can u please help me in solving ?
Most helpful comment
@thesavvygreek @tsdorsey Thanks for that. Figured it out!
It's a Serverless Framework bug. They broke it with their latest release. Here is the issue somebody else opened for it - https://github.com/serverless/serverless/issues/3972
For now you can use
1.17.0by doing the following. I'll add this to the tutorial.And then
serverless deployagain.