
CloudFront - API Gateway Security: API Key Rotation
Ensuring Secure Communication Between CloudFront and API Gateway: Automated API Key Rotation using AWS Lambda.
API keys in Amazon API Gateway are primarily used for tracking usage, throttling, and identifying API consumers. According to AWS best practices, API keys act as unique identifiers that allow you to:
- Monitor usage: Identify which consumers are making requests.
- Limit rates: Manage request frequency through usage plans.
- Set quotas: Define request limits within specific time frames.
- Handle billing: Link API usage to particular consumers.
API Keys as Infrastructure Communication Secrets:
While API keys should not be used for user authentication, they can function as shared secrets between AWS services to manage infrastructure-level access. In this scenario, we use API keys as communication "tokens" between CloudFront and API Gateway to:
- Block direct API Gateway access from the internet.
- Guarantee traffic passes through CloudFront for caching and security advantages.
- Establish a controlled entry point for your API infrastructure.
This method considers the API key as an infrastructure-level access control, similar to using a firewall rule: it's about managing service-to-service communication, not authenticating end users.
Nevertheless, similar to any security credential, API keys carry inherent risks. If compromised, stolen, or leaked, they may grant unauthorized access, leading to severe repercussions. This highlights the importance of regularly rotating keys as a crucial preventive measure in a strong cloud security strategy.
Amazon API Gateway includes a "key store" feature that allows you to create or import API keys, which are securely stored within Amazon API Gateway.
API Gateway also enhances security through Resource Policies — JSON-formatted policies that control access based on IP addresses, VPC endpoints, IAM principals, and other conditions. However, for infrastructure-level service communication control, API key rotation provides a practical, automated solution that complements these other security mechanisms.
Architecture Overview
Today, we will delve into a serverless approach for automating API key rotation between API Gateway and CloudFront using AWS Lambda. This solution notably enhances our security by eliminating the manual process, which is often susceptible to errors or oversight.

The solution architecture includes:
- CloudFront manages client requests, passing them through to the API Gateway while including the API key in a custom header labeled "x-api-key." This key serves only as a "shared secret" between these two AWS services, establishing a secure and authenticated communication channel.
- An API Gateway set up to require an API key for each request, granting access solely through CloudFront and blocking direct internet access.
- A Lambda function that executes the API key rotation process.
- An EventBridge Scheduler sends required parameters and triggers the Lambda request monthly.
Note: All resources are created in a single AWS account.
This setup requires customers to access the API exclusively via CloudFront, as they lack knowledge or access to the internal communication API key. This separation enhances security and allows for better traffic control to your API.
This automated solution provides numerous significant benefits:
- Enhanced Security: Frequent API key rotation greatly minimizes vulnerability periods against potential compromises.
- Reduced Operational Load: Removes the necessity for manual rotations, allowing personnel to focus on more valuable tasks.
- Compliance and Audit: Aids in meeting security standards and maintains a clear log of rotation timings.
- Zero Downtime: The architecture guarantees a smooth key transition without any service disruptions.
Automatic Rotation Implementation
The Python-based Lambda function automates the rotation process entirely. It features a comprehensive logging system that aids in troubleshooting and auditing. The function executes these operations:
- Check existing API keys: First, locate the specified usage plan to check if an associated API key already exists.
- Generate a new API key: Produce a new API key on the API Gateway using the provided name.
- Associate the key: Link the new key to the configured usage plan.
- Update the CloudFront distribution: Update the "x-api-key" header in the CloudFront origin configuration with the new key value.
- Remove the old key: After the CloudFront update is finalized, delete the old API key to maintain a clean environment.
The function needs four configuration parameters, which can be provided as environment variables or through the event that triggers it:
USAGE_PLAN_ID: API Gateway usage plan ID
DISTRIBUTION_ID: CloudFront distribution ID
ORIGIN_ID: Origin ID in distribution
API_KEY_NAME: Name for the new API key
Example:
JSON
{"API_KEY_NAME": "kloudpepper-api-key","DISTRIBUTION_ID": "E1MTSB8DGIOBI2","ORIGIN_ID": "api-gateway-origin","USAGE_PLAN_ID": "0aj0l3"}
I will provide the code to set up this solution in your AWS environment, consisting of two main components:
- Terraform Code: This code is used to provision essential infrastructure components such as API Gateway , CloudFront , Lambda , and EventBridge Scheduler . It provides examples of creating these resources and the necessary configurations for their integration.
Multi-Account Scenario
The proposed solution assumes that all resources—API Gateway, CloudFront, and Lambda—are hosted within a single AWS account. However, in enterprise environments, it's typical for these services to be spread across multiple accounts to enhance security, support organizational needs, or create clear divisions of responsibility.
If the API Gateway is in a different account from CloudFront, the rotation procedure necessitates extra considerations:
- Cross-account roles: To modify the relevant resources, the Lambda function must assume a role in the target account.
- Cross-account trust configuration: Establishing trust relationships between the IAM roles of both accounts is essential.
- Lambda location: It's essential to determine in which account to deploy the Lambda function—whether in the account where CloudFront resides or where API Gateway is available—given that it requires permissions in both accounts.
I'm providing another Python code for use in the Lambda function, specifically for multi-account situations. Simply include one additional parameter in the already mentioned ones:
ROLE_ARN: The ARN of the role established in the target account that the Lambda will assume.
This cross-account setup introduces some complexity but greatly enhances the security stance by adhering to the principle of least privilege and separating responsibilities among accounts.
This is just one way to incorporate advanced security measures into your AWS architectures. Feel free to tailor and refine this solution to meet the unique requirements of your infrastructure.
Best wishes, and I look forward to our next meeting. Thank you!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article