Reserved environment variable names should not be overridden in Lambda functions

Why is this an issue?

AWS Lambda reserves certain environment variable names for its internal operations and runtime management. These reserved variables, such as '_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_REGION', and others, are automatically set by the Lambda service and contain critical information about the function’s execution context. When application code overrides these reserved environment variables by assigning new values to them, it can disrupt the Lambda runtime’s ability to function correctly. The Lambda service relies on these variables to manage function execution, implement tracing, handle authentication, and maintain proper communication with other AWS services.

What is the potential impact?

Overriding reserved environment variables can lead to unpredictable Lambda function behavior, runtime failures, broken tracing and monitoring capabilities, authentication issues with AWS services, and difficulty in debugging production problems. This can result in service outages and degraded system reliability.

How to fix it

Avoid modifying any environment variable names that are reserved by AWS Lambda. Use custom environment variable names that do not conflict with AWS Lambda’s reserved names. Always prefix your custom environment variables with a unique identifier or use descriptive names that clearly indicate they are application-specific.

Code examples

Noncompliant code example

import os

def lambda_handler(event, context):
  os.environ['AWS_REGION'] = "us-west-2"  # Noncompliant: overriding AWS Lambda reserved environment variable
  return {"statusCode": 200}

Compliant solution

import os

def lambda_handler(event, context):
  os.environ['APP_REGION'] = "us-west-2" # Compliant: using custom environment variable names
  return {"statusCode": 200}

Resources

Documentation

Standards

CWE-20: Improper Input Validation