AWs lambda - enable events in slack fails - amazon-web-services

I created an AWS Lambda function with the following default (Hello world example) code.
def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
I also added an API gateway as a trigger and when tested with curl, I can successfully retrieve the 'Hello from Lambda Message'
curl https://xxxxxxxxxxxxx.execute-api.us-east-1.amazonaws.com/default/test
"Hello from Lambda!"
Then, as I want to build a slackbot, I enable events and tested the api-gateway url in slack
slack app event
I'm failing to understand why there is no challenge nor token being sent in slack post to the api gateway URL
Besides the fact that I should be able to catch the challenge and return it to complete de verification process, there nothing being sent from slack challenge POST message (I should at least see the code:200 and the "Hello from Lambda!" message in the body anyway)
Following this article, I was expecting to see something like this, but mine has an empty response
Slack Enable events from article
Any clues? This is a new workspace and a new slack app, so it is possible that I forgot to set it correctly.
Thanks

I was having the same problem as you. I followed this example and got it to work: https://medium.com/analytics-vidhya/create-and-distribute-a-slack-bot-with-python-and-aws-in-1-hour-41c4a6c0f99d
The issue with my API was that initially I created an API in API Gateway of type REST. When I made an API of type HTTP, everything worked.

Related

How can we know that whether message is forwarded to the destination properly in AWS Lambda

I have configured a lambda function which forwards incoming messages to multiple endpoints. Also I have added a AWS API Gateway as a trigger, so if I invoke API gateway endpoint I can forward that message to multiple endpoints. I want to check whether the messages are been forwarded to the desired destination or not, also I want to check integrity of that message.
Can anyone suggest a proper way to check for the same apart from returning status code 200 in response.
Have you checked the official tutorial about building an API and returning response. Basically you can return additional variables in response. Like in JS based lambda function
exports.handler = async (event, context, callback) => {
callback(null, {
"greeting": greeting
});
}
So can call the endpoints and validate the messages has been delivered or not and return state in form of variables. Please let me know if you have additional questions.

How to integrate Appsync api in android

I have given an amazon api to integrate. But I have no idea how to use this api
mutation createTrail {
createTruckTrailer(input:{truckId: "077",trailer:["AB22D"]}){
result
}
}
The snippet you've been given is an example of a GraphQL query, which can be sent to a GraphQL-enabled endpoint, such as the one you've been given which is hosted using AWS AppSync. A GraphQL query is structured differently than a REST api call; think of it as a structured way of making REST calls. Requests are sent to the ApiUrl you pasted above in a POST HTTP request, with a request body that looks like:
{
"query": "mutation createTrail {\n createTruckTrailer(input:{truckId: \"077\",trailer:[\"AB22D\"]}){\n result }\n }",
"operationName": "createTrail",
"variables": {}
}
However additional headers are necessary to authenticate with IAM. The response from the server will include the result as JSON. I highly recommend spending just a few minutes to become a little more familiar with GraphQL here: https://graphql.org/learn/
To make calls to this AppSync endpont from Android, take a look at the Amplify android client, which explains how to get started here (Skip step 4): https://aws-amplify.github.io/docs/android/start, and then setup your client to authenticate with IAM to your backend here: https://aws-amplify.github.io/docs/android/api#iam
Once your amplify client is fully set up, you can make the GraphQL Mutation shown above by following the steps here: https://aws-amplify.github.io/docs/android/api#import-sdk-and-config
Use retrofit with rxJava or coroutines.

Github Webhooks secret with AWS API Gateway

I am trying to have a Github Webhook launch an AWS Lambda I have.
The best way I can figure out how to do that is to use AWS API Gateway, the issue is security.
Github Webhooks will only send a secret with the POST call.
I can't find any way to have AWS API Gateway to verify this signature.
Or where I can add this functionality.
I assume I can write an AWS Lambda Authorizer.
But this is a lot of code in different places, starting to see the need for serverless framework.
Any easier setup within AWS I do not know about for this?
Came here because I was trying to integrate a Github webhook with AWS lambda and ran into the same problem as the OP. At the time of writing I believe the best solution is to include verification code in the main lambda, as others have suggested.
On the AWS Computer Blog from September 2017:
Enhanced request authorizer Lambda functions receive an event object that is similar to proxy integrations. It contains all of the information about a request, excluding the body.
Source: Using Enhanced Request Authorizers in Amazon API Gateway (amazon.com)
You can't perform HMAC as recommended by Github, because AWS authorizer lambdas don't give you access to the body of the HTTP request, which you need in order to compare digests.
This is a shame, because HMAC seems to be a pretty standard way of securing an endpoint that responds to a webhook. See for example this blog post, Webhooks do’s and dont’s: what we learned after integrating +100 APIs (restful.io). Twitter and Stripe do something similar:
Securing webhooks (twitter.com)
Checking Webhook Signatures(stripe.com)
To make the approach described above work, if you're using API Gateway you'll need to make sure that the header that contains the hash signature is forwarded as part of the event argument to the lambda. To do that, follow these instructions: How do I pass custom headers through Amazon API Gateway to an AWS Lambda function using custom Lambda integration for further processing? (amazon.com)
I couldn't find a way to do this with API Gateway. I validated within the LAMBDA using (Python).
High level overview : Calculate HMAC signature with GITHUB_SECRET then compare to the signature passed from Github.
You can obviously simplify, intentionally verbose for readability. There may be better ways, but I couldn't find one.
Make sure your Webhook is configured for application/json. Hopefully this helps someone else.
import logging
import json
import hmac
import hashlib
import re
from urllib.parse import unquote
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
GITHUB_SECRET = 'SECRET FROM GITHUB CONSOLE'
def lambda_handler(event, context):
logger.info("Lambda execution starting up...")
incoming_signature = re.sub(r'^sha1=', '', event['headers']['X-Hub-Signature'])
incoming_payload = unquote(re.sub(r'^payload=', '', event['body']))
calculated_signature = calculate_signature(GITHUB_SECRET, incoming_payload.encode('utf-8'))
if incoming_signature != calculated_signature:
logger.error('Unauthorized attempt')
return {
'statusCode': 403,
'body': json.dumps('Forbidden')
}
logger.info('Request successfully authorized')
# do stuff in Lambda
return {
'statusCode': 200,
'body': json.dumps(f'Work in progress')
}
def calculate_signature(github_signature, githhub_payload):
signature_bytes = bytes(github_signature, 'utf-8')
digest = hmac.new(key=signature_bytes, msg=githhub_payload, digestmod=hashlib.sha1)
signature = digest.hexdigest()
return signature

SurveyMonkey - Create Webhook with AWS API Gateway as Subscription Url

I am trying to Integrate SurveyMonkey with my backend.
This is the flow:
(1) We create a webhook(https://developer.surveymonkey.com/api/v3/#webhooks) using POST method from PHP, with Subscription url as an AWS API Gateway.
(2) When user completes a survey, SurveyMonkey invokes the subscription Url (API Gateway), which in turn calls a Lambda function to update the database.
The problem is when i try to give a API Gateway url as the subscription Url, SurveyMonkey returns a Bad Request response. If i use a general .php page, the webhook is getting created successfully.
In the conversation with SurveyMonkey Support Team, they say, the API Gateway should return a 200 response for HEAD request. I am not sure how to set this up in AWS.
Can anyone who has implemented / integrated, API Gateway with SurveyMonkey please guide me on how to solve this issue?
Here is the conversation with SurveyMonkey Support Team:
Thanks for getting back in touch. I just spoke with my colleagues on
the development team and they noted that there shouldn't be an issue
in using a lamda function for your subscription_URL. As long as it
accepts HEAD and POST requests and returns a 200. I hope this helps
you out; of course, please let me know if I can assist further.
Thanks for getting back in touch. I wanted to confirm that the lambda
function needs to return a 200 to a HEAD request in order for us to
enable the webhook properly. This isn't done after the webhook is
cerated, but as the webhook is created. It still seems like the
lambda function isn't responding, or responding correctly, as it is
created, so it will continue to fail. I hope this helps clarify;
please let me know if I can assist further.
One way or another, you need to get the API Gateway to respond to HEAD requests. There are a lot of ways to do this. You could add a HEAD method to the resource of your URL. You can do that in the API Gateway console under the resource section when you're editing you api. You can send the HEAD requests to a lambda function and have that function return a 200 status code for appropriate HEAD requests. You can set up a mock return in the api integration request, but you'll need to set up the correct integration details. You can also just set ANY lambda proxy integration and deal with everything on the lambda side.
Once you have something setup you should be able to test with curl:
curl -I http://yourUrl.example.com

AWS API Gateway - Change http proxy status code

I cretaed a http proxy method in my API Gateway to a remote CRM system I need to send data to.
The thing is that the CRM return all its responses as 200, and notifies for success or failure inside the response body, for example :
Hi wish to know, if there is any way inside the method to check the response using lambda function and change the status code accordingly.
You will have to modify your lambda to change the response and include an error message to model in API Gateway. This blog post is a great resource for configuring these mappings.