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, you need the fol­low­ing.

  name: aws
  runtime: nodejs8.10
    - Effect: Allow
      Principal: "*"
      Action: execute-api:Invoke
        - execute-api:/*/GET/index.html

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"

Like what you’re read­ing? Check out my video course Pro­duc­tion-Ready Server­less and learn the essen­tials of how to run a server­less appli­ca­tion in pro­duc­tion.

We will cov­er top­ics includ­ing:

  • authen­ti­ca­tion & autho­riza­tion with API Gate­way & Cog­ni­to
  • test­ing & run­ning func­tions local­ly
  • CI/CD
  • log aggre­ga­tion
  • mon­i­tor­ing best prac­tices
  • dis­trib­uted trac­ing with X-Ray
  • track­ing cor­re­la­tion IDs
  • per­for­mance & cost opti­miza­tion
  • error han­dling
  • con­fig man­age­ment
  • canary deploy­ment
  • VPC
  • secu­ri­ty
  • lead­ing prac­tices for Lamb­da, Kine­sis, and API Gate­way

You can also get 40% off the face price with the code ytcui. Hur­ry though, this dis­count is only avail­able while we’re in Manning’s Ear­ly Access Pro­gram (MEAP).