How to create IP-protected endpoints with API Gateway and Lambda

If you haven’t been pay­ing close atten­tion you might have missed the API Gate­way announce­ment for resource poli­cies. It lat­er played a key role in sup­port­ing API Gate­way pri­vate end­points — a way to put your API inside a pri­vate VPC.

To con­fig­ure resource poli­cies with the Server­less frame­work, you need to upgrade to v1.28.0 or lat­er. If you want to restrict access to the GET /index.html end­point to the IP 217.128.123.174, you need the fol­low­ing.

provider:
name: aws
runtime: nodejs8.10
resourcePolicy:
- Effect: Allow
Principal: "*"
Action: execute-api:Invoke
Resource:
- execute-api:/*/GET/index.html
Condition:
IpAddress:
aws:SourceIp:
- 217.128.123.174

Nice and easy!

There are a cou­ple of things to note:

  • You can imple­ment IP black­list­ing by chang­ing Effect to Deny.
  • If you change the resource pol­i­cy in the API Gate­way con­sole, it won’t take effect until you deploy the API. No such wor­ries with the server­less frame­work, as sls deploy would deploy the API for you as part of the Cloud­For­ma­tion update.
  • You can mix IP and IAM con­di­tions for dif­fer­ent end­points in the same API. But, IP and IAM con­di­tions don’t work for a private API, which is not pub­licly acces­si­ble and is required for VPC pri­vate end­points.
  • When you access the API from EC2 or ECS, you need to whitelist the pub­lic IP of the instance, or the NAT Gate­way if the instance is not asso­ci­at­ed with a pub­lic IP.

After you set up IP whitelist­ing on the end­point, you will get an error like this if you attempt to access it from an IP that has not been whitelist­ed.

{ 
"Message": "User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-central-1:********3770:io75qg1rvf/test/GET/index.html"
}

read original article here