AI coding assistants like Claude need tight permission controls, especially when they run in shared Lambda environments. Using Attribute‑Based Access Control (ABAC) with IAM tags lets you grant just‑the‑right access without hard‑coding identities.
Why ABAC Matters for AI Agents
When you hand a Claude‑powered helper to a Lambda function, you are giving it the ability to read source files, write logs, maybe even store temporary results in S3. If every helper gets the same wide‑open role, a single buggy or compromised instance can reach data it should never see.
Attribute‑Based Access Control (ABAC) is a way of saying “let a request do something only if it carries the right attributes.” In AWS, those attributes are IAM tags – simple key/value pairs you attach to roles, users, or even a single session.
Think of a library that lets you borrow books based on the genre tag you wear on your badge. A “science‑fiction” badge lets you walk to the sci‑fi shelf, while a “history” badge points you to the past‑section. You don’t need a separate key for each shelf; the badge’s attribute does the work.
With ABAC you can:
- Keep the same role for many agents, but restrict each agent by the tag it presents.
- Add a new project simply by adding a new tag value—no new IAM role to spin up.
- Enforce the principle of least privilege (give only the permissions an agent truly needs).
In plain English: ABAC lets you say “Claude can read code files only if it tells AWS it belongs to project = codeassist.” The permission is tied to the tag, not to a hard‑coded role name.
The hidden cost of static roles
Most teams start with a static IAM role per agent, like ClaudeCodeAssistantRole. When you add a second project, you clone the role, change a few policies, and hope you didn’t miss anything. Over time the list of roles explodes, and a tiny mistake (e.g., forgetting to remove an S3 bucket permission) can become a security hole.
ABAC with tags lets you replace that growing list with a single, well‑scoped role and a set of tags that tell AWS who the request is on behalf of.
Setting Up IAM Tags for Your Claude Agent
Before you can use tags in a policy, the tags have to exist on the IAM resource that will be assumed. In our case the resource is an IAM role that the Lambda will assume at runtime.
Step 1 – Create a role (or reuse an existing one)
import { IAMClient, CreateRoleCommand, TagResourceCommand, } from "@aws-sdk/client-iam"; // The IAM client talks to the IAM service in your AWS account. const iam = new IAMClient({}); // Define a role that Lambda will later assume. // The trust policy says “Lambda services are allowed to assume this role”. const roleName = "ClaudeAgentBaseRole"; const assumeRolePolicy = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole", }, ], }; await iam.send( new CreateRoleCommand({ RoleName: roleName, AssumeRolePolicyDocument: JSON.stringify(assumeRolePolicy), Description: "Base role for Claude agents – permissions are gated by tags", }) ); CreateRoleCommand creates the role. The trust policy (the JSON inside AssumeRolePolicyDocument) tells AWS which services are allowed to call sts:AssumeRole on this role.
Step 2 – Attach a tag that identifies the project
// Tag the role with a generic key/value that we will later require. // In this example the key is "project" and the value is "codeassist". await iam.send( new TagResourceCommand({ ResourceArn: `arn:aws:iam::${process.env.AWS_ACCOUNT_ID}:role/${roleName}`, Tags: [{ Key: "project", Value: "codeassist" }], }) ); The IAM tag is just a piece of metadata: a key (project) and a value (codeassist). You can attach many tags, but for our ABAC example we only need one.
Tip: Tagging the role itself is optional for ABAC; the important tag is the session tag you pass when you assume the role. Tagging the role helps you stay organized in the console.
Creating an IAM Role with Tag Conditions
Now that the role exists, we write a permission policy that only grants access when the request carries the right tag. The policy lives on the same role we just created.
The policy JSON
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowClaudeWhenProjectTagMatches", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "arn:aws:s3:::codeassist-bucket/*", "arn:aws:logs:*:*:log-group:/aws/lambda/Claude*:*" ], "Condition": { "StringEquals": { "aws:RequestTag/project": "codeassist" }, "ForAllValues:StringEquals": { "aws:TagKeys": ["project"] } } } ] } -
StringEqualsonaws:RequestTag/projectsays “the request must have a tag named project whose value is codeassist.” -
aws:TagKeysensures the request actually includes theprojecttag; otherwise the condition fails.
Attach the policy to the role
import { IAMClient, PutRolePolicyCommand, } from "@aws-sdk/client-iam"; const iam = new IAMClient({}); await iam.send( new PutRolePolicyCommand({ RoleName: roleName, PolicyName: "ClaudeAgentABACPolicy", PolicyDocument: JSON.stringify({ // (Paste the JSON from above here) Version: "2012-10-17", Statement: [ { Sid: "AllowClaudeWhenProjectTagMatches", Effect: "Allow", Action: [ "s3:GetObject", "s3:PutObject", "logs:CreateLogStream", "logs:PutLogEvents", ], Resource: [ "arn:aws:s3:::codeassist-bucket/*", "arn:aws:logs:*:*:log-group:/aws/lambda/Claude*:*", ], Condition: { StringEquals: { "aws:RequestTag/project": "codeassist", }, "ForAllValues:StringEquals": { "aws:TagKeys": ["project"], }, }, }, ], }), }) ); Key takeaway: The only thing that can make this policy grant permissions is the presence of the correct tag on the assumed session. If the tag is missing or has a different value, the policy evaluates to “deny,” and AWS returns
AccessDenied.
The gotcha that trips many engineers
IAM evaluates the condition on the assumed role, not on the original Lambda execution role. If you forget to forward the session tags in the AssumeRole call, the request looks tag‑less to the policy and fails silently with AccessDenied. The role itself appears correctly attached, so the error can be confusing at first glance.
Using the Role in a Node.js Lambda
Below is a minimal Lambda written in TypeScript that:
- Calls STS (
Security Token Service) to assume the ABAC‑tagged role, passing the required session tag. - Uses the temporary credentials to call Claude’s HTTP API with
fetch. - Handles the
AccessDeniedExceptionthat occurs when tags are missing or mismatched.
Lambda handler (src/handler.ts)
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts"; import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda"; import fetch from "node-fetch"; // The ARN of the role we created earlier. const ROLE_ARN = process.env.CLAUDE_AGENT_ROLE_ARN!; // STS client – used to exchange the Lambda's own credentials for // temporary ones that carry the session tag. const sts = new STSClient({}); /** * Helper: ask STS for temporary credentials that include the * project=codeassist tag. */ async function getTaggedCredentials() { const command = new AssumeRoleCommand({ RoleArn: ROLE_ARN, RoleSessionName: "ClaudeAgentSession", // TagSession is the crucial piece – it attaches the tag // to the *assumed* role session. Tags: [{ Key: "project", Value: "codeassist" }], // Optional: keep the credentials for an hour (default) DurationSeconds: 3600, }); const response = await sts.send(command); if (!response.Credentials) { throw new Error("Failed to obtain temporary credentials"); } return { accessKeyId: response.Credentials.AccessKeyId!, secretAccessKey: response.Credentials.SecretAccessKey!, sessionToken: response.Credentials.SessionToken!, }; } /** * Main Lambda entry point. */ export const handler = async (event: any) => { try { // 1️⃣ Get temporary, tagged credentials. const creds = await getTaggedCredentials(); // 2️⃣ Call Claude's API – we use fetch, passing the temporary creds // as an Authorization header (the real Claude API uses an API key, // but many internal wrappers accept AWS sigv4 signing; adjust as needed). const response = await fetch("https://api.anthropic.com/v1/complete", { method: "POST", headers: { "Content-Type": "application/json", // Example of passing AWS creds; replace with your actual auth method. "X-Aws-Access-Key": creds.accessKeyId, "X-Aws-Secret-Key": creds.secretAccessKey, "X-Aws-Session-Token": creds.sessionToken, }, body: JSON.stringify({ prompt: "Write a one‑line summary of the event payload:", max_tokens: 64, }), }); if (!response.ok) { // If Claude returns an error, surface it. const errorBody = await response.text(); throw new Error(`Claude API error: ${response.status} ${errorBody}`); } const data = await response.json(); console.log("Claude reply:", data); return { statusCode: 200, body: JSON.stringify(data) }; } catch (err) { // 3️⃣ Specific handling for missing tags. if (err.name === "AccessDeniedException") { console.error( "Access denied – most likely the session tag is missing or wrong." ); } else { console.error("Unexpected error:", err); } return { statusCode: 500, body: JSON.stringify({ error: err.message }) }; } }; What each line does
- Import statements bring in the AWS SDK clients we need.
-
ROLE_ARNcomes from an environment variable set when you deploy the Lambda. -
getTaggedCredentials()builds anAssumeRoleCommandthat includesTags. TheTagsarray is what makes ABAC work. - The Lambda then uses
fetchto call Claude. In a real world setup you would probably sign the request with SigV4 or use an API key; the example shows where the temporary credentials would be used. - The
catchblock looks forAccessDeniedException, which is the exact error you get when the tag condition fails.
Helpful tip: Always log the full error object (including
err.name) when debugging IAM issues. The name tells you whether you’re dealing with a missing tag (AccessDeniedException) or a different problem (e.g., network timeout).
Deploying the Lambda (quick snippet)
import { LambdaClient, CreateFunctionCommand, UpdateFunctionConfigurationCommand, } from "@aws-sdk/client-lambda"; const lambda = new LambdaClient({}); await lambda.send( new CreateFunctionCommand({ FunctionName: "ClaudeAgentHandler", Runtime: "nodejs22.x", Role: process.env.LAMBDA_EXECUTION_ROLE_ARN, // the role that *creates* the AssumeRole call Handler: "dist/handler.handler", Code: { // Assume you have zipped the compiled TS output into S3 S3Bucket: "my-deploy-bucket", S3Key: "claude-agent.zip", }, // Provisioned concurrency is optional – remember it costs money even when idle. // Uncomment if you need low latency. // ProvisionedConcurrencyConfig: { ProvisionedConcurrentExecutions: 5 }, Environment: { Variables: { CLAUDE_AGENT_ROLE_ARN: "arn:aws:iam::123456789012:role/ClaudeAgentBaseRole", }, }, }) ); Plain English recap: The Lambda itself runs under a basic execution role (just enough to call
sts:AssumeRole). The heavy lifting – access to S3, CloudWatch logs, and Claude – is granted only after the session tagproject=codeassistis attached.
Testing and Debugging Permission Errors
Even with careful code, the first few runs often hit a snag. Below are practical steps to isolate the problem.
1️⃣ Verify the session tag is actually sent
Add a temporary log right after AssumeRoleCommand:
console.log("Assumed role credentials with tags:", response.AssumedRoleUser?.Arn); If the log shows the ARN without :assumed-role/ suffix, the call likely failed before tags were attached.
2️⃣ Use the IAM Policy Simulator
The console’s Policy Simulator lets you paste a policy, specify a role ARN, and add “request tags.” Check the Result column:
- If the simulator says Deny and points to
aws:RequestTag/project, you know the tag value is not matching the policy.
3️⃣ Look at CloudWatch logs for AccessDeniedException
When the Lambda catches the error, it prints the stack trace. The message often contains a short phrase:
User: arn:aws:sts::123456789012:assumed-role/ClaudeAgentBaseRole/ClaudeAgentSession is not authorized to perform: s3:GetObject Notice the assumed role part – it confirms the request is evaluated on the assumed role, not the original Lambda execution role.
4️⃣ Common mis‑configurations
| Gotcha | Symptom | Fix |
|---|---|---|
Missing aws:TagKeys condition | Policy passes StringEquals but still denies | Add "aws:TagKeys": ["project"] so the engine knows the tag must be present. |
| AssumeRole session duration too short | Long‑running job stops after ~1 hour with ExpiredTokenException | Increase DurationSeconds (max 12 h) or refresh credentials periodically. |
| Permission boundary blocks the policy | Even with correct tags, call fails | Ensure the permission boundary attached to the role includes the actions you need. |
| SCP (Service Control Policy) denies the action | Deny even though role policy allows | Review the organization’s SCPs; they have the highest priority. |
Node 22 require(esm) breakage in Lambda layers | Module not found errors at cold start | Either compile to CommonJS or use the type: "module" flag in package.json. |
Key point: The most frequent cause of silent failures is forgetting to pass the session tags when assuming the role. The role may look attached, but without the tag the ABAC condition never matches, resulting in an
AccessDeniedresponse.
5️⃣ Automated test script (optional)
A quick Node script can programmatically verify the tag flow:
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts"; const sts = new STSClient({}); async function testTagFlow() { const cmd = new AssumeRoleCommand({ RoleArn: process.env.CLAUDE_AGENT_ROLE_ARN, RoleSessionName: "TagTest", Tags: [{ Key: "project", Value: "codeassist" }], }); const resp = await sts.send(cmd); console.log("Assumed ARN:", resp.AssumedRoleUser?.Arn); } testTagFlow().catch(console.error); Run it locally with the same IAM credentials your Lambda uses. If it prints an ARN, the tag path works; otherwise the error will point you to the missing permission or tag.
The Takeaway
In plain English: ABAC with IAM tags gives you a clean, scalable way to say “only Claude agents that belong to project = codeassist may read from codeassist‑bucket.”
- ABAC ties permissions to attributes (tags) instead of static role names, making it easier to add or retire projects.
- The session tag you supply in
AssumeRoleis the key that unlocks the permission policy; without it the policy evaluates to deny. - A single IAM role, a simple tag‑condition policy, and a few lines of TypeScript replace dozens of static roles.
- Common pitfalls include forgetting to forward tags, confusing IAM evaluation order (explicit deny wins), and hidden limits like the default 1‑hour session duration.
- Debugging works best with the IAM Policy Simulator, CloudWatch logs that show the assumed role ARN, and a tiny test script that prints the assumed ARN.
By following the steps in this post, you can protect your Claude‑powered Lambda functions with fine‑grained, tag‑driven access—without the overhead of managing a forest of static roles. Happy tagging!
Transparency notice
This article was written with the help of an AI system — Groq (GPT OSS 120B).
Published: 2026-12-04 · Primary focus: IAM
All code blocks are intended to be correct and runnable, but please verify them
against the official docs for the tools mentioned before using in production.Find an error? Drop a comment — corrections are always welcome.