Secrets Rotation In AWS SAM Managed Applications







Secrets Rotation in AWS SAM Applications | Serverless Security













Secrets Rotation in AWS SAM-Managed Applications

Implement automated secrets rotation in your AWS SAM applications with our security best practices guide.

Download Full 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.

Simple Analogy: Think of secrets rotation like changing the locks on your doors. Even if someone made a copy of your key, regularly changing the locks ensures they can’t get in with an old key.

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

ServiceBest ForRotation SupportIntegration with SAM
AWS Secrets ManagerDatabase credentials, API keysBuilt-in rotationNative integration
Systems Manager Parameter StoreConfiguration values, license keysRequires custom solutionNative integration
AWS KMSEncryption keysAutomatic key rotationBuilt-in support
Environment VariablesSimple configurationNo rotation supportBasic support
🔑

Real-World Implementation

A fintech company using AWS SAM managed to reduce credential-related security incidents by 82% after implementing automated rotation:

  1. Database credentials rotated every 45 days
  2. API keys rotated every 30 days
  3. All rotation events logged to CloudTrail
  4. Zero-downtime rotation during business hours

Implementing Secrets Rotation in SAM Templates

[Secrets Manager]
↓ Rotation Trigger
[Rotation Lambda] → [Database]
↑
[SAM Application]

Secrets rotation architecture in AWS SAM applications

1

Store Secrets in Secrets Manager

Define your secret in the SAM template:

YAML

Resources:
  DatabaseSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: "Database credentials"
      GenerateSecretString:
        SecretStringTemplate: '{"username": "admin"}'
        GenerateStringKey: "password"
        PasswordLength: 32
        ExcludeCharacters: '"@/'
      Tags:
        - Key: App
          Value: MyServerlessApp

2

Create Rotation Lambda Function

Implement the rotation logic in a Lambda function:

Python

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']
    )

3

Configure Automatic Rotation

Attach the rotation schedule to your secret:

YAML

  RotationSchedule:
    Type: AWS::SecretsManager::RotationSchedule
    Properties:
      SecretId: !Ref DatabaseSecret
      RotationLambdaARN: !GetAtt RotationLambda.Arn
      RotationRules:
        AutomaticallyAfterDays: 45
        Duration: "2h"
        ScheduleExpression: "cron(0 2 ? * MON-FRI *)"

4

Grant Lambda Access to Secrets

Add necessary permissions to your Lambda execution role:

YAML

  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

YAML

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:

YAML

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:

  1. Verify Lambda execution role permissions
  2. Check resource-based policies on secrets
  3. 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
Important: Always test your rotation process in a staging environment before deploying to production. A failed rotation in production can cause application downtime.

Advanced Rotation Patterns

Multi-Region Secrets Synchronization

For global applications, implement cross-region secrets replication:

YAML

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:

  1. Create custom Lambda rotation function
  2. Implement service-specific API calls
  3. Handle multi-step rotation process
  4. 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:

  1. Start with your most critical credentials first
  2. Implement gradual rollout with monitoring
  3. Regularly audit rotation processes
  4. 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);
});


1 thought on “Secrets Rotation In AWS SAM Managed Applications”

  1. Pingback: Secure Lambda Deployment Pipelines With AWS SAM - Serverless Saviants

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top