A Journey in Learning

Extracting SourceIP’s from API Gateways using Nodejs or Python

I have been trying to use NodeJS to extract user IP addresses from an API get request sent to lambda. I used the following mapping template:

{
    "sourceIP" : "$context.identity.sourceIp"
}

I then looked around online and found the following lambda code to extract the source address from the response sent to lambda.

'use strict';
console.log('Loading function');
exports.handler = (event, context, callback) => {
    console.log('SourceIP =', event.identity.sourceIp);
    callback(null, event.identity.sourceIp);
};

however using this method I kept getting the error:

{
  "errorType": "TypeError",
  "errorMessage": "Cannot read property 'sourceIp' of undefined",
  "trace": [
    "TypeError: Cannot read property 'sourceIp' of undefined",
    "    at Runtime.exports.handler (/var/task/index.js:4:46)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
  ]
}

After looking into the error message, I realized that the snippet event.identity.sourceip was referencing the response JSON incorrectly. Instead I should be using event.sourceip and take out identity completely.

After trying this again now I receive a null response with the log reading:

INFO    SourceIP = undefined

Now I am a bit stuck, I processed the same mapping template with Python instead using this code:

def lambda_handler(event, context):
var= event['sourceIP']

I suspect its an easy fix to get this working in Nodejs, I will continue working on this.