Whitelist IP addresses for Lambda function URLs

Written by: Chirag (Srce Cde)


Whitelist IP address for function URL
Whitelist IP address for function URL

Lambda function URLs feature is the recent addition to the AWS Lambda service. With a lambda function URL, one can invoke the lambda function via a unique URL similar to the invocation of any API endpoint with respective methods.

In this article, we will configure/add the functionality to validate the IP address of the incoming requests via function URL which will enable us to only serve the requests originating from the whitelisted IP addresses and block the rest while Auth Type is selected as None.

As of now, we cannot leverage resource policy to whitelist IP addresses for lambda function URLs since that feature is not available. So, here we will write a simple python function to add that functionality as a part of the lambda function code base.

Hands-On

Create the lambda function and the function URL for the same.


Lambda function + Function URL
Lambda function + Function URL

As a next step, update the source code of the function from my GiHub repository and deploy.

Post deploying the code, add the environment variable IP_RANGE with the list of IP addresses, CIDR blocks (for IP range) that need to be whitelisted. If you do not add the environment variable, then by default it will return status code 500 with the message Unauthorized for all incoming requests.

Note: The status code and message can be modified within the code.


Setting ENV variable
Setting ENV variable

The updated lambda function code will check & validate the origin IP address of the request against the whitelisted IP addresses as a part of the IP_RANGE environment variables.

Now, we are all set to test it.

Testing

For testing, we will use Postman and the setup will look as below.



The endpoint will return 500 Forbidden if the IP address is not whitelisted as a part of an IP_RANGE environment variable.


Result, before whitelisting the IP

After whitelisting the IP address as a part of an IP_RANGE environment variable, the endpoint will return status code 200 with an appropriate response.


Result, after whitelisting the IP

However, here we have a few disadvantages when we decide to choose this methodology.

  • For all invalid calls (Invocation calls from the IP addresses which are not whitelisted), the lambda function will get triggered each time and that will add up the cost for each unwanted call
  • For all valid calls (Invocation calls from the IP addresses which are whitelisted), the validation of IP address logic will add up to the execution time with added relevant cost
  • Cannot whitelist private IP addresses (For ex: Private VPCs IP ranges)

For a detailed end-to-end, step-by-step setup, you can refer to the video below.



Thank you!



YouTube       Twitter       GitHub       LinkedIn