
The Runtime Shield: Enforcing Least-Privilege IAM for AWS Lambda
A complete, interactive guide to mastering AWS Lambda runtime security. Learn how AWS SAM policy templates work, dive deep into Identity vs. Resource policies, explore invisible SAM mechanics, and enforce least-privilege.
Series: The Shift-Left Serverless Pipeline. (5 articles)
- …
- 3The Runtime Shield: Enforcing Least-Privilege IAM for AWS Lambda This article
In Part 1 of this series, we secured our deployment pipeline using OIDC. In Part 2, we built automated gates to block vulnerable code from ever reaching AWS. Our deployment process is now a fortress.
But what happens if a vulnerability, like a zero-day exploit, slips through and an attacker gains remote execution inside your AWS Lambda function?
This is where Runtime Security comes in. If an attacker breaches your function, what are they allowed to do? If you gave your Lambda function administrative permissions just to make it "work" during development, that attacker now has the keys to your entire AWS account.
In this article, we will explore how to apply the Principle of Least Privilege (PoLP) to your AWS SAM templates. We will dissect the difference between Identity and Resource policies, explore the built-in policy templates AWS SAM offers, and learn how to grant our functions exactly what they need—and nothing more.
The Danger of the Wildcard (*)
When we are frustrated and just want our code to connect to a database or a storage bucket, it is incredibly tempting to use a wildcard policy.
Take a look at this AWS SAM YAML snippet.
Resources: MyProcessDataFunction: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: com.example.App::handleRequest Runtime: java21 Policies: - Statement: - Effect: Allow Action: 's3:*' Resource: '*'💬 Interactive Checkpoint: Before reading further, drop a comment below: What are the two massive security risks in the YAML snippet above?
If you spotted
Action: 's3:*' and Resource: '*' , you are spot on.- The Action Flaw:
s3:*allows this function to read, write, delete, and modify permissions for buckets. Does a data processing function really need to delete buckets?
- The Resource Flaw:
Resource: '*'means this function can perform those actions on every single bucket in your AWS account.
If compromised, this single Lambda function could be used to wipe out all your organization's backups.
The "Invisible" Permissions: Logs and Traces
A common question developers ask when adopting Least Privilege is: "If I strictly limit my Lambda to only access DynamoDB, won't I break my CloudWatch logs? Don't I need to give it permissions to write logs and X-Ray traces?"
This is a brilliant question. For a high-standard operational scenario, your Lambda must be able to output structured logs and traces.
Fortunately, AWS SAM helps us out here. When you define
Policies in a SAM template (like we will do below), SAM automatically attaches the AWSLambdaBasicExecutionRole in the background. This managed policy grants your function the exact permissions it needs to create log streams and put log events into Amazon CloudWatch ( logs:CreateLogGroup , logs:CreateLogStream , logs:PutLogEvents ).For AWS X-Ray tracing, SAM makes it even easier. You don't need to write a manual IAM policy. You simply enable tracing in your template, and SAM automatically attaches the
AWSXRayDaemonWriteAccess policy! MyDataFunction: Type: AWS::Serverless::Function Properties: Runtime: java21 Tracing: Active # SAM automatically adds X-Ray IAM permissions here!
Level 1: AWS SAM Built-in Policy Templates (The Fast Track)
To help developers avoid wildcards without writing complex JSON IAM policies from scratch, AWS SAM provides dozens of built-in Policy Templates. These are predefined sets of permissions scoped to specific resources.
Here are a few powerful templates you can use immediately:
-
S3ReadPolicy: Grants read-only access to a specific bucket.
-
DynamoDBCrudPolicy: Grants Create, Read, Update, and Delete access to a specific table.
-
SQSPollerPolicy: Grants permissions to poll messages from a specific SQS queue.
-
SNSPublishMessagePolicy: Grants permissions to publish messages to a specific SNS topic.
Here is how easily you can implement one:
Resources: MyDataBucket: Type: AWS::S3::Bucket
MyProcessDataFunction: Type: AWS::Serverless::Function Properties: Handler: com.example.App::handleRequest Runtime: java21 Policies: - S3ReadPolicy: BucketName: !Ref MyDataBucketWhy is this better? The function can only execute
s3:GetObject and s3:ListBucket . Furthermore, by referencing !Ref MyDataBucket , it is cryptographically restricted to that specific bucket. It cannot read data from your HR records bucket.
Level 2: Crafting Custom Inline IAM Policies (Granular Precision)
SAM Policy Templates cover common use cases, but enterprise applications often require granular control. For example, what if you are using Amazon DynamoDB and your function only needs to update specific items, but should never be allowed to scan the entire table?
For the highest level of security, we define custom inline policies. Here is how you write a strictly scoped policy in your
template.yaml . UpdateOrderFunction: Type: AWS::Serverless::Function Properties: Handler: com.example.UpdateOrder::handleRequest Runtime: java21 Policies: - Statement: - Effect: Allow Action: - dynamodb:UpdateItem - dynamodb:PutItem Resource: !GetAtt OrdersTable.Arn- Targeted Actions: We explicitly list
dynamodb:UpdateItemanddynamodb:PutItem. The function physically cannot execute adynamodb:Scan.
- Targeted Resources: We use
!GetAtt OrdersTable.Arnto dynamically fetch the exact Amazon Resource Name (ARN) of our specific table.
Core Conceptual Pillar: Identity-Based vs. Resource-Based Policies
To truly master IAM in serverless, we must understand that our Lambda function requires two different types of security checks. This is often the biggest stumbling block for beginners.
1. Identity-Based Policies (The "Outbound" Shield)
- The Question: "What is this Lambda function allowed to do?"
- Where it lives: Attached to the Lambda's IAM Execution Role.
- How to use it: Use this to grant your Lambda permission to talk to other AWS services (like we did with the DynamoDB inline policy above).
2. Resource-Based Policies (The "Inbound" Shield)
- The Question: "Who is allowed to invoke this Lambda function?"
- Where it lives: Attached directly to the Lambda function itself.
- How to use it: Use this when an external service (like Amazon API Gateway, EventBridge, or Amazon S3) needs to trigger your function.
Best Practice: You rarely have to write these manually in SAM! When you define an
Events source in your SAM template, SAM automatically generates the Resource Policy allowing that specific service to invoke your function. ApiBackendFunction: Type: AWS::Serverless::Function Properties: Runtime: java21 Events: ApiEvent: Type: Api Properties: Path: /orders Method: post# SAM sees this Event block and invisibly creates a Resource Policy # allowing ONLY this specific API Gateway to trigger the function.The Golden Rule
Think of it like a secure building:
- Resource Policy: The security guard at the front door checking the ID of the API Gateway trying to get in to trigger your code.
- Identity Policy: The keycard your code wears around its neck, dictating which rooms (S3, DynamoDB) it can enter once it is running.
Level 3 (Pro-Tier): IAM Condition Keys & Permissions Boundaries
If you want to elevate your DevSecOps skills to a senior level, you can add
Condition blocks to your IAM policies.Even if a Lambda has permission to read an S3 bucket, you can use a Condition Key to mandate that it can only do so if the request originates from a specific VPC (
aws:SourceVpce ) or if the target resource has a specific tag ( aws:ResourceTag/Environment: Production ).Furthermore, organizations often implement Permissions Boundaries. This is an advanced IAM feature where cloud administrators define the maximum possible permissions a developer can grant their Lambda function. Even if you write
Policies: AdministratorAccess in your SAM template, the boundary will silently cap your function's power, preventing privilege escalation.
Your DevSecOps Challenge
Security is a muscle we build through practice. Open one of your current personal projects or a repository at work. Check your Lambda execution roles.
Are there any
* characters hiding in your outbound Identity policies? Are you accidentally leaving your inbound Resource policies too open?I challenge you to pick one overly permissive function this week and refactor it using either a SAM Policy Template or a Custom Inline Policy. Shrink that blast radius!
In the final installment of this series, we will focus on Observability. We have secured our CI/CD pipeline and locked down our runtime environment, but how do we actually know if someone is probing our defenses? We will explore structured logging, metrics, and threat detection.
Let's discuss: Have you ever accidentally broken a production feature while trying to enforce Least Privilege? How did you troubleshoot the IAM denial? Share your battle stories in the comments below!
Series: The Shift-Left Serverless Pipeline. (5 articles)
- …
- 3The Runtime Shield: Enforcing Least-Privilege IAM for AWS Lambda This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article