ABAC mit IAM-Tags: Feingranulare Zugriffsrechte für Claude-AI-Agents in Lambda
KI-Coding-Assistenten wie Claude brauchen in geteilten Lambda-Umgebungen strikte Rechtevergabe. Attribute-Based Access Control mit IAM-Tags erlaubt passgenaue Berechtigungen, ohne Identitäten fest im Code zu hinterlegen.

KI-Codierungsassistenten wie Claude benötigen strenge Berechtigungssteuerungen, insbesondere wenn sie in gemeinsam genutzten Lambda-Umgebungen laufen. Der Einsatz von attributbasierter Zugriffskontrolle (ABAC) mit IAM-Tags erlaubt es, exakt die richtigen Zugriffe zu gewähren, ohne Identitäten fest im Code zu verankern.
Wenn man ein Claude-basiertes Hilfsprogramm an eine Lambda-Funktion übergibt, gibt man ihm die Fähigkeit, Quelldateien zu lesen, Logs zu schreiben und eventuell sogar temporäre Ergebnisse in S3 abzulegen. Wenn jedes Hilfsprogramm dieselbe weit geöffnete Rolle erhält, kann eine einzige fehlerhafte oder kompromittierte Instanz auf Daten zugreifen, die sie niemals sehen dürfte.
Attributbasierte Zugriffskontrolle (ABAC) ist eine Art zu sagen: Eine Anfrage darf etwas nur tun, wenn sie die richtigen Attribute mitbringt. In AWS sind diese Attribute IAM-Tags, einfache Schlüssel-Wert-Paare, die man an Rollen, Benutzer oder sogar eine einzelne Session anhängt.
Stellen Sie sich eine Bibliothek vor, in der Sie Bücher ausleihen dürfen, basierend auf dem Genretag, das Sie auf Ihrem Ausweis tragen. Ein „Science-Fiction“-Ausweis lässt Sie zum Science-Fiction-Regal gehen, während ein „Geschichte“-Ausweis Sie zur Abteilung für Historisches führt. Sie brauchen keinen separaten Schlüssel für jedes Regal; das Attribut auf dem Ausweis erledigt die Arbeit.
Klar formuliert: ABAC erlaubt die Aussage „Claude darf Codedateien nur lesen, wenn es AWS mitteilt, dass es zu project = codeassist gehört.“ Die Berechtigung ist an das Tag gebunden, nicht an einen fest kodierten Rollennamen.
Die meisten Teams starten mit einer statischen IAM-Rolle pro Agent, etwa ClaudeCodeAssistantRole. Fügt man ein zweites Projekt hinzu, klont man die Rolle, ändert einige Policies und hofft, nichts übersehen zu haben. Mit der Zeit explodiert die Liste der Rollen, und ein winziger Fehler (zum Beispiel ein vergessenes Entfernen einer S3-Bucket-Berechtigung) kann zu einer Sicherheitslücke werden.
ABAC mit Tags erlaubt es, diese wachsende Liste durch eine einzige, sauber abgegrenzte Rolle und eine Reihe von Tags zu ersetzen, die AWS mitteilen, in wessen Auftrag die Anfrage erfolgt.
Bevor Sie Tags in einer Policy verwenden können, müssen die Tags auf der IAM-Ressource existieren, die übernommen werden soll. In unserem Fall ist die Ressource eine IAM-Rolle, die die Lambda-Funktion zur Laufzeit übernimmt.
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", } ) ); Enter fullscreen mode Exit fullscreen mode CreateRoleCommand erstellt die Rolle. Die Trust Policy (das JSON innerhalb von AssumeRolePolicyDocument) teilt AWS mit, welche Dienste sts:AssumeRole auf dieser Rolle aufrufen dürfen.
// 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" } ], } ) ); Enter fullscreen mode Exit fullscreen mode Das IAM-Tag ist einfach ein Stück Metadaten: ein Schlüssel (project) und ein Wert (codeassist). Sie können viele Tags anhängen, aber für unser ABAC-Beispiel benötigen wir nur eines.
Tipp: Das Taggen der Rolle selbst ist für ABAC optional; das wichtige Tag ist das Session-Tag, das Sie beim Übernehmen der Rolle übergeben. Das Taggen der Rolle hilft Ihnen lediglich, in der Konsole den Überblick zu behalten.
Nun, da die Rolle existiert, schreiben wir eine Berechtigungspolicy, die nur dann Zugriff gewährt, wenn die Anfrage das richtige Tag mitbringt. Die Policy liegt auf derselben Rolle, die wir gerade erstellt haben.
{ "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" ] } } } ] } Enter fullscreen mode Exit fullscreen mode StringEquals auf aws:RequestTag/project besagt: Die Anfrage muss ein Tag namens project mit dem Wert codeassist haben. aws:TagKeys stellt sicher, dass die Anfrage tatsächlich das project-Tag enthält; andernfalls schlägt die Bedingung fehl. Policy an die Rolle anhängen: 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" ], }, }, }, ], } ), } ) ); Enter fullscreen mode Exit fullscreen mode Zentrale Erkenntnis: Das Einzige, was diese Policy Berechtigungen gewähren kann, ist das Vorhandensein des korrekten Tags auf der übernommenen Session. Fehlt das Tag oder hat es einen anderen Wert, wertet die Policy zu „deny“ aus, und AWS gibt AccessDenied zurück.
IAM wertet die Bedingung auf der übernommenen Rolle aus, nicht auf der ursprünglichen Lambda-Ausführungsrolle. Vergessen Sie, die Session-Tags im AssumeRole-Aufruf weiterzureichen, erscheint die Anfrage für die Policy als tag-los und schlägt stillschweigend mit AccessDenied fehl. Die Rolle selbst scheint korrekt angehängt zu sein, wodurch der Fehler auf den ersten Blick verwirrend wirken kann.
Im Folgenden eine minimale Lambda-Funktion in TypeScript, die Folgendes tut:
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 } ) }; } }; Enter fullscreen mode Exit fullscreen mode Was jede Zeile bewirkt: Die Import-Anweisungen bringen die benötigten AWS-SDK-Clients ins Spiel. ROLE_ARN stammt aus einer Umgebungsvariable, die beim Deployment der Lambda-Funktion gesetzt wird. getTaggedCredentials() erstellt ein AssumeRoleCommand, das Tags enthält.
Das Tags-Array ist es, was ABAC funktionsfähig macht. Die Lambda-Funktion ruft Claude anschließend per fetch auf. In einer realen Umgebung würde man die Anfrage vermutlich mit SigV4 signieren oder einen API-Schlüssel verwenden; das Beispiel zeigt, an welcher Stelle die temporären Zugangsdaten genutzt würden.
Der catch-Block prüft auf AccessDeniedException, exakt der Fehler, der auftritt, wenn die Tag-Bedingung fehlschlägt. Ein hilfreicher Tipp: Logge beim Debuggen von IAM-Problemen immer das vollständige Fehlerobjekt (einschließlich err.name). Der Name verrät dir, ob es um ein fehlendes Tag geht (AccessDeniedException) oder um ein anderes Problem (z. B. einen Netzwerk-Timeout).
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, // die Rolle, die den AssumeRole-Aufruf *erzeugt* Handler: "dist/handler.handler", Code: { // Annahme: die kompilierte TS-Ausgabe wurde als ZIP nach S3 hochgeladen S3Bucket: "my-deploy-bucket", S3Key: "claude-agent.zip", }, // Provisioned Concurrency ist optional – beachte, dass sie auch im Leerlauf Geld kostet. // Auskommentieren, falls du niedrige Latenz benötigst. // ProvisionedConcurrencyConfig: { ProvisionedConcurrentExecutions: 5 }, Environment: { Variables: { CLAUDE_AGENT_ROLE_ARN: "arn:aws:iam::123456789012:role/ClaudeAgentBaseRole", }, }, } ) ); Enter fullscreen mode Exit fullscreen mode Zusammenfassung in einfachen Worten: Die Lambda-Funktion selbst läuft unter einer einfachen Ausführungsrolle (gerade ausreichend, um sts:AssumeRole aufzurufen). Die eigentliche Arbeit – Zugriff auf S3, CloudWatch-Logs und Claude – wird erst gewährt, nachdem das Session-Tag project=codeassist angehängt wurde.
Selbst bei sorgfältigem Code läuft die ersten paar Ausführungen oft etwas schief. Hier folgen praktische Schritte, um das Problem einzugrenzen.
Füge direkt nach dem AssumeRoleCommand ein temporäres Log hinzu:
console. log ( "Assumed role credentials with tags:", response. AssumedRoleUser?. Arn ); Enter fullscreen mode Exit fullscreen mode Wenn das Log den ARN ohne den Suffix:assumed-role/ zeigt, ist der Aufruf vermutlich gescheitert, bevor die Tags angehängt wurden.
Mit dem Policy Simulator in der Konsole kannst du eine Policy einfügen, einen Rollen-ARN angeben und „request tags“ hinzufügen. Prüfe die Spalte Result:
Wenn die Lambda-Funktion den Fehler abfängt, gibt sie den Stack-Trace aus. Die Meldung enthält häufig einen kurzen Satz:
User: arn:aws:sts::123456789012:assumed-role/ClaudeAgentBaseRole/ClaudeAgentSession is not authorized to perform: s3:GetObject Enter fullscreen mode Exit fullscreen mode Beachte den Teil assumed-role – er bestätigt, dass die Anfrage anhand der angenommenen Rolle bewertet wird, nicht anhand der ursprünglichen Lambda-Ausführungsrolle.
Wichtiger Punkt: Die häufigste Ursache für stille Fehler ist, dass man beim Annehmen der Rolle vergisst, die Session-Tags mitzugeben. Die Rolle wirkt vielleicht korrekt angehängt, aber ohne das Tag greift die ABAC-Bedingung nie, und das Ergebnis ist eine AccessDenied-Antwort.
Ein kurzes Node-Skript kann den Tag-Fluss programmatisch überprüfen:
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 ); Enter fullscreen mode Exit fullscreen mode Führe es lokal mit denselben IAM-Zugangsdaten aus, die auch deine Lambda-Funktion verwendet. Wenn ein ARN ausgegeben wird, funktioniert der Tag-Pfad; andernfalls weist dich der Fehler auf die fehlende Berechtigung oder das fehlende Tag hin.
In einfachen Worten: ABAC mit IAM-Tags bietet dir einen sauberen, skalierbaren Weg zu sagen: „Nur Claude-Agents, die zum Projekt codeassist gehören, dürfen aus codeassist-bucket lesen.“
Wenn du die Schritte aus diesem Beitrag befolgst, kannst du deine Claude-basierten Lambda-Funktionen mit fein abgestuften, tag-gesteuerten Zugriffsrechten schützen, ohne den Aufwand, einen Wald an statischen Rollen verwalten zu müssen. Viel Spaß beim Taggen!
Dieser Artikel wurde mit Hilfe eines KI-Systems erstellt – Groq (GPT OSS 120B).
Veröffentlicht: 2026-12-04 · Schwerpunkt: IAM
Alle Codeblöcke sollen korrekt und lauffähig sein, aber prüfe sie vor dem produktiven Einsatz bitte gegen die offizielle Dokumentation der genannten Tools.
Fehler gefunden? Schreib einen Kommentar – Korrekturen sind jederzeit willkommen.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
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.
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.
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.
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.
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.
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", } ) ); Enter fullscreen mode Exit fullscreen mode CreateRoleCommand creates the role. The trust policy (the JSON inside AssumeRolePolicyDocument ) tells AWS which services are allowed to call sts:AssumeRole on this role.
// 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" } ], } ) ); Enter fullscreen mode Exit fullscreen mode 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.
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.
{ "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" ] } } } ] } Enter fullscreen mode Exit fullscreen mode StringEquals on aws:RequestTag/project says “the request must have a tag named project whose value is codeassist.” aws:TagKeys ensures the request actually includes the project tag; 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" ], }, }, }, ], } ), } ) ); Enter fullscreen mode Exit fullscreen mode 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.
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.
Below is a minimal Lambda written in TypeScript that:
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 } ) }; } }; Enter fullscreen mode Exit fullscreen mode What each line does Import statements bring in the AWS SDK clients we need. ROLE_ARN comes from an environment variable set when you deploy the Lambda. getTaggedCredentials() builds an AssumeRoleCommand that includes Tags.
The Tags array is what makes ABAC work. The Lambda then uses fetch to 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 catch block looks for AccessDeniedException, 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).
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", }, }, } ) ); Enter fullscreen mode Exit fullscreen mode 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 tag project=codeassist is attached.
Even with careful code, the first few runs often hit a snag. Below are practical steps to isolate the problem.
Add a temporary log right after AssumeRoleCommand:
console. log ( "Assumed role credentials with tags:", response. AssumedRoleUser?. Arn ); Enter fullscreen mode Exit fullscreen mode If the log shows the ARN without:assumed-role/ suffix, the call likely failed before tags were attached.
The console’s Policy Simulator lets you paste a policy, specify a role ARN, and add “request tags.” Check the Result column:
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 Enter fullscreen mode Exit fullscreen mode Notice the assumed role part – it confirms the request is evaluated on the assumed role, not the original Lambda execution role.
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 AccessDenied response.
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 ); Enter fullscreen mode Exit fullscreen mode 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.
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.”
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!
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.