Secrets Rotation in AWS SAM-Managed Applications
Implement automated secrets rotation in your AWS SAM applications with our security best practices guide.
Why Secrets Rotation Matters in Serverless Applications
In AWS SAM-managed applications, secrets like API keys, database credentials, and encryption keys are the digital keys to your kingdom. Regular rotation of these secrets is a critical security practice that reduces the risk of unauthorized access and limits the potential damage from credential leaks.
Traditional approaches to secrets management often fail in serverless environments because:
- Lambda functions are stateless and ephemeral
- Manual rotation doesn’t scale with hundreds of functions
- Hard-coded credentials create security vulnerabilities
- Distributed systems make consistent rotation challenging
AWS Services for Secrets Management
Service | Best For | Rotation Support | Integration with SAM |
---|---|---|---|
AWS Secrets Manager | Database credentials, API keys | Built-in rotation | Native integration |
Systems Manager Parameter Store | Configuration values, license keys | Requires custom solution | Native integration |
AWS KMS | Encryption keys | Automatic key rotation | Built-in support |
Environment Variables | Simple configuration | No rotation support | Basic support |
Real-World Implementation
A fintech company using AWS SAM managed to reduce credential-related security incidents by 82% after implementing automated rotation:
- Database credentials rotated every 45 days
- API keys rotated every 30 days
- All rotation events logged to CloudTrail
- Zero-downtime rotation during business hours
Implementing Secrets Rotation in SAM Templates
Store Secrets in Secrets Manager
Define your secret in the SAM template:
Resources: DatabaseSecret: Type: AWS::SecretsManager::Secret Properties: Description: "Database credentials" GenerateSecretString: SecretStringTemplate: '{"username": "admin"}' GenerateStringKey: "password" PasswordLength: 32 ExcludeCharacters: '"@/' Tags: - Key: App Value: MyServerlessApp
Create Rotation Lambda Function
Implement the rotation logic in a Lambda function:
import boto3 import json def lambda_handler(event, context): client = boto3.client('secretsmanager') # Parse the secret ARN and token from the event arn = event['SecretId'] token = event['ClientRequestToken'] # Check if this is the correct token for the current stage metadata = client.describe_secret(SecretId=arn) if not metadata['RotationEnabled']: raise ValueError(f"Secret {arn} is not enabled for rotation") # Implement rotation logic here # 1. Create new credentials # 2. Update the database # 3. Update the secret # Finalize the rotation client.update_secret_version_stage( SecretId=arn, VersionStage="AWSCURRENT", MoveToVersionId=token, RemoveFromVersionId=metadata['VersionId'] )
Configure Automatic Rotation
Attach the rotation schedule to your secret:
RotationSchedule: Type: AWS::SecretsManager::RotationSchedule Properties: SecretId: !Ref DatabaseSecret RotationLambdaARN: !GetAtt RotationLambda.Arn RotationRules: AutomaticallyAfterDays: 45 Duration: "2h" ScheduleExpression: "cron(0 2 ? * MON-FRI *)"
Grant Lambda Access to Secrets
Add necessary permissions to your Lambda execution role:
RotationLambdaRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole Policies: - PolicyName: SecretsRotationPolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - secretsmanager:DescribeSecret - secretsmanager:GetSecretValue - secretsmanager:PutSecretValue - secretsmanager:UpdateSecretVersionStage Resource: !Ref DatabaseSecret
Security Best Practices
Principle of Least Privilege
Ensure your rotation Lambda has only the permissions it absolutely needs:
- Restrict access to specific secrets
- Limit database permissions to credential rotation
- Use resource-based policies where possible
Rotation Strategy
RotationRules: AutomaticallyAfterDays: 30 # Rotate every month Duration: "1h" # Complete within 1 hour ScheduleExpression: "cron(0 1 ? * MON *)" # Rotate Monday at 1 AM
Monitoring and Alerting
Implement CloudWatch alerts for rotation failures:
Resources: RotationFailureAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: "SecretsRotationFailure" AlarmDescription: "Alert when secrets rotation fails" MetricName: "Errors" Namespace: "AWS/Lambda" Statistic: "Sum" Period: 300 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: "GreaterThanOrEqualToThreshold" Dimensions: - Name: "FunctionName" Value: !GetAtt RotationLambda.FunctionName AlarmActions: - "arn:aws:sns:us-east-1:123456789012:SecurityAlerts"
Troubleshooting Common Issues
Rotation Failing Permissions
Symptom: Rotation Lambda fails with “Access Denied” errors.
Solution:
- Verify Lambda execution role permissions
- Check resource-based policies on secrets
- Ensure correct AssumeRole permissions
Database Connection Issues
Symptom: New credentials work in Lambda but not in application.
Solution:
- Check VPC configuration and security groups
- Verify DNS resolution in Lambda environment
- Test connectivity using Lambda test function
Advanced Rotation Patterns
Multi-Region Secrets Synchronization
For global applications, implement cross-region secrets replication:
Resources: ReplicationPolicy: Type: AWS::IAM::Policy Properties: PolicyName: SecretsReplicationPolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - secretsmanager:ReplicateSecretToRegions Resource: !Ref DatabaseSecret Roles: - !Ref RotationLambdaRole
Custom Rotation for Third-Party Services
For services not natively supported by Secrets Manager:
- Create custom Lambda rotation function
- Implement service-specific API calls
- Handle multi-step rotation process
- Implement comprehensive error handling
Securing Your Serverless Future
Implementing automated secrets rotation in AWS SAM applications is a critical security practice that:
- Reduces the attack surface of your applications
- Meets compliance requirements (HIPAA, PCI DSS, GDPR)
- Minimizes manual operational overhead
- Ensures continuous security posture improvement
Key implementation recommendations:
- Start with your most critical credentials first
- Implement gradual rollout with monitoring
- Regularly audit rotation processes
- Include rotation in your security training
Additional Resources
`;
// Create a Blob and download
const blob = new Blob([htmlContent], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = this.download;
document.body.appendChild(a);
a.click();
// Clean up
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
});