kevinhakanson.com

Redacting tokens in Lambda function events

May 25, 2025 #javascript #python #security #aws #lambda

When I write an AWS Lambda function in JavaScript/TypeScript that takes some sort of auth token in the event, I take care to redact it from any logs. The code below is similar to what I use, using the replacer parameter of JSON.stringify to replace the actual token with the string [REDACTED].

console.log(
    JSON.stringify(
        event,
        (key, value) => {
            if (key == 'authToken')
              return '[REDACTED]';
            return value;
        },
        2,
    )
);

I recently needed similar functionality for a Python-based Lambda function and used Python JSON Encoders and Decoders. I create a RedactedEncoder class of my own to use like print(json.dumps(event, cls=RedactedEncoder)). Below is my version of the code:

class RedactedEncoder(json.JSONEncoder):
    def iterencode(self, o, _one_shot=False):
        processed_obj = self._process_object(o)
        return super().iterencode(processed_obj, _one_shot)

    def _process_object(self, obj):
        if isinstance(obj, dict):
            result = {} # avoid modifying the original
            for key, value in obj.items():
                if key in ['authToken']:
                    result[key] = "[REDACTED]"
                else:
                    result[key] = self._process_object(value)
            return result
        elif isinstance(obj, list):
            return [self._process_object(item) for item in obj]
        else:
            return obj

Note, there are some sharp edges if your object contains properties that are not JSON serializable (like Decimal), so look at adding default=str to your json.dumps call.


Kevin Hakanson

Multi-Cloud Certified Architect | DevSecOps | AppSec | Web Platform | Speaker | Learner | Builder
LinkedIn | Bluesky | X | GitHub | Stack Overflow | Credly

© 2025 Kevin Hakanson (built with Gatsby)