
Protect AI coding agents from credential theft on Amazon Bedrock
Learn how attackers who steal credentials can use AI coding agents like Claude Code or Codex to run their own model workloads on your Bedrock account at your expense, a kind of attack called LLMjacking. Developing in a secure environment includes signing in through IAM Identity Center so they get short-lived credentials, give agents a role that can only call approved models, block long-term keys across the organization with a service control policy, and set alerts for unusual spend and activity.
When your developers run AI coding agents such as Claude Code from Anthropic or Codex from OpenAI on Amazon Bedrock , credential theft can let an attacker run their own workloads on models in your account while you pay for the usage. This kind of abuse is one form of LLMjacking, short for large language model (LLM) hijacking, and the charges start as soon as the attacker sends requests.
You can close the most common paths to this abuse without changing how your developers work. A typical starting point is an ordinary cloud credential: a long-term access key committed to a repository, a key file left on a laptop, or a session token that someone pastes into a phishing page. Temporary credentials, a narrowly scoped role, and a few organization-wide controls reduce that exposure.
AI coding agents raise the stakes because they run with the developer's access. They read local files, run shell commands, and can follow instructions hidden in content they read, a technique called prompt injection. If an admin profile or a long-term key sits in ~/.aws, the agent can use it, and so can anyone who steers the agent.
In this post, we show you how to move developer and agent access to temporary credentials, limit what those credentials can do, block long-term keys across your organization, and get an alert when model spend looks unusual.
Solution overview
The solution has four parts:
- Temporary credentials. Developers sign in through AWS IAM Identity Center with the AWS Command Line Interface (AWS CLI) and receive credentials that expire after a few hours.
- A least-privilege role. A permission set grants the agent permission to call the models you approve.
- Organization-wide controls. A service control policy (SCP) in AWS Organizations stops principals in member accounts from creating long-term AWS Identity and Access Management (IAM) access keys or long-term Amazon Bedrock API keys.
- Spend and activity alerts. AWS Cost Anomaly Detection flags unusual spend, Amazon GuardDuty flags unusual model invocations, and Amazon EventBridge rules alert you on the AWS CloudTrail events that matter.
Prerequisites
To follow along, you need:
- An organization in AWS Organizations with all features and SCPs turned on, and access to the management account or a delegated administrator account for policies.
- IAM Identity Center turned on and connected to your identity source, with multi-factor authentication (MFA) required at sign-in.
- Permissions to create and assign permission sets in IAM Identity Center.
- Access to the models you plan to use in Amazon Bedrock, such as Anthropic Claude models for Claude Code or OpenAI models for Codex.
- A CloudTrail trail that logs management events in each account, such as an organization trail. EventBridge receives CloudTrail events only when a trail is logging.
- An email address for cost alerts.
For this post, we use AWS CLI 2.37.9, Claude Code 2.1.231, and Codex CLI 0.136.0. The aws login command requires AWS CLI 2.32.0 or later.
Use temporary credentials instead of long-term keys
AWS credentials fall into two groups. Long-term credentials, such as IAM user access keys (IDs starting with AKIA) and long-term Amazon Bedrock API keys, have no expiration date. They keep working until someone finds and deletes them, which makes them easy to leak and hard to contain. They end up in repositories, .env files, shell history, and chat messages, and an AI coding agent that can read your home directory can read them too. Temporary credentials (IDs starting with ASIA) are issued by AWS Security Token Service (AWS STS) and expire after a few hours. If one is copied or stolen, it stops working shortly afterward, and the attacker must steal a fresh one.
Make temporary credentials the default for everything that calls Amazon Bedrock. When a user or workload assumes an IAM role, whether through aws sso login or another mechanism, AWS STS issues temporary credentials that expire automatically. This removes long-lived secrets that attackers can steal and reuse.
Treat Amazon Bedrock API keys as a last resort. If a specific tool can’t use the AWS credential chain, use a short-term Amazon Bedrock API key, which is generated from your existing temporary session and expires with it. Avoid long-term API keys. Later in this post, a service control policy (SCP) blocks creating and using them across your organization, so this becomes a guardrail rather than a habit that developers must remember.
The following examples show where temporary credentials come from, depending on where the agent runs:
- Developer workstation with IAM Identity Center: The developer signs in with aws sso login and receives temporary credentials for the permission set’s role.
- Developer workstation without IAM Identity Center: The developer signs in with aws login and receives temporary credentials based on their console sign-in. For details, refer to Login for AWS local development using console credentials .
- Servers outside AWS: AWS Identity and Access Management Roles Anywhere (IAM Roles Anywhere) lets a server use its certificate to obtain temporary role credentials.
Create a least-privilege permission set for Amazon Bedrock
Your developers probably have broad access to their day-to-day work, but the agent doesn’t need it. All it needs is gateway access, model invocation, and web search. A dedicated permission set grants only those actions, so even a hijacked agent can’t create users, read secrets, or enable new services, the first things attackers typically try.
The following inline policy allows streaming and non-streaming calls to a cross-region inference profile for Claude Sonnet 4.5 and the foundation model behind it. Replace <ACCOUNT-ID> with your account ID and add a pair of resources for each Anthropic model you approve. Cross-Region inference can route requests to other Regions, so the foundation model Amazon Resource Name (ARN) uses a wildcard for the Region.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "InvokeApprovedModels", "Effect": "Allow", "Action": [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream", "bedrock:GetInferenceProfile" ], "Resource": [ "arn:aws:bedrock:us-east-1: <ACCOUNT-ID>:inference-profile/us.anthropic.claude-sonnet-4-5-20250929-v1:0", "arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-5-20250929-v1:0" ] }, { "Sid": "ListInferenceProfiles", "Effect": "Allow", "Action": "bedrock:ListInferenceProfiles", "Resource": "*" } ] } Codex calls OpenAI models through the Responses API. With the amazon-bedrock-runtime provider, Codex uses the Amazon Bedrock endpoint, and the Responses API there also checks bedrock:InvokeModel on your account's default project. Add the OpenAI inference profile and foundation model ARNs to the policy, plus arn:aws:bedrock:*: <ACCOUNT-ID>:project/default. If a tool uses the Amazon Bedrock Mantle endpoint, such as Codex with the amazon-bedrock provider, it needs bedrock-mantle:CreateInference instead, because Mantle has its own IAM actions. For details, refer to Making inference requests .
To create the permission set
- Open the IAM Identity Center console.
- Under Multi-account permissions, choose Permission sets.
- Choose Create permission set.
- On the Select permission set type page, select Custom permission set, and then choose Next.
- On the Specify policies and permission boundary page, expand Inline policy, enter the preceding policy, and then choose Next.
- On the Specify permission set details page, for Permission set name, enter BedrockAgentAccess. For Session duration, select 8 hours, and then choose Next.
- On the Review and create page, choose Create.
Next, assign the permission set to the developer group in each account where developers use Amazon Bedrock. For instructions, refer to Assign user or group access to AWS accounts .
Configure developer workstations for temporary credentials
Each developer creates a named profile that signs in through IAM Identity Center. The credentials it produces expire when the session ends, so a copied credential stops working within hours. A long-term key keeps working until someone notices it and deletes it.
To configure an IAM Identity Center profile
- In a terminal, enter aws configure sso.
- When prompted, enter a session name, your AWS access portal URL, and the Region where IAM Identity Center is enabled.
- Press Enter to accept the default registration scope.
- In the browser window that opens, sign in and approve the request.
- In the terminal, select the AWS account and the BedrockAgentAccess role.
- Enter a default Region, an output format, and the profile name bedrock-agent.
- Enter
aws sts get-caller-identity --profile bedrock-agentand confirm that the ARN in the output containsAWSReservedSSO_BedrockAgentAccess.
When the session expires, developers enter aws sso login --profile bedrock-agent to sign in again. For more details, refer to Configuring IAM Identity Center authentication with the AWS CLI .
When you audit workstations, check the access key IDs. IDs that start with AKIA are long-term keys, and IDs that start with ASIA are temporary. Replace any AKIA key you find in a config file, environment variable, or repository.
Configure the coding agent
The agent needs to use the new profile, and it shouldn't be able to read the credential cache in
~/.aws . Claude Code handles the second part with two controls. Permission deny rules block its built-in file tools, and the sandbox blocks the shell commands it runs. The following settings point Claude Code at Amazon Bedrock through the bedrock-agent profile and pin the model that the permission set allows. The awsAuthRefresh setting starts the browser sign-in when the credentials expire. The permissions.deny rules and the sandbox.filesystem.denyRead entry keep the agent away from ~/.aws and .env files. The allowUnsandboxedCommands setting stops Claude Code from retrying a blocked command outside the sandbox, where denyRead doesn't apply. The failIfUnavailable setting makes Claude Code refuse to start if the sandbox can't run, instead of running commands unsandboxed. The sandbox doesn't run on native Windows, so with this setting Claude Code won't start there.
{ "env": { "CLAUDE_CODE_USE_BEDROCK": "1", "AWS_PROFILE": "bedrock-agent", "AWS_REGION": "us-east-1", "ANTHROPIC_MODEL": "us.anthropic.claude-sonnet-4-5-20250929-v1:0" }, "awsAuthRefresh": "aws sso login --profile bedrock-agent", "permissions": { "deny": ["Read(~/.aws/**)", "Read(**/.env)"] }, "sandbox": { "enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "filesystem": { "denyRead": ["~/.aws"] } } } To configure Claude Code
- Open
~/.claude/settings.jsonin a text editor, or create the file if it doesn't exist.
- Add the preceding settings, and save the file.
- Start Claude Code.
- Enter
/statusand confirm that the provider is Amazon Bedrock.
- Enter
/sandboxand confirm that the sandbox is on. On the Overrides tab, confirm that Strict sandbox mode is on.
- Enter
/permissionsand confirm that the deny rules appear.
Developers can change their own settings file, so for a team rollout, put these settings in a managed settings file instead. Users can't override managed settings. For more information, refer to Settings files and precedence and Claude Code on Amazon Bedrock .
Codex reads the same profile through the standard AWS credential chain. For setup steps, refer to Use ChatGPT Work and Codex with Amazon Bedrock . The Codex CLI sandbox blocks network access and limits writes to the workspace by default, but sandboxed commands can still read your home directory, including
~/.aws . To block those reads, add a permission profile to ~/.codex/config.toml that extends the built-in :workspace profile:
# Keep the default workspace sandbox and deny reads of the AWS credential cache default_permissions = "bedrock-agent" [permissions.bedrock-agent] extends = ":workspace" [permissions.bedrock-agent.filesystem] "~/.aws" = "deny" Permission profiles are in beta as of this writing, and they don't combine with the older sandbox_mode setting. For details, refer to Permissions .
* One side effect is that if the agent runs aws s3 ls in a sandboxed shell, the AWS CLI can’t read the cache and fails. *
Block long-term keys with a service control policy
Temporary credentials help only if people stop creating long-term ones. Developers fall back to access keys when sign-in feels slow, and an SCP removes that option across your organization.
The following SCP denies creation of IAM user access keys and service-specific credentials, which include long-term Amazon Bedrock API keys. It also denies use of existing long-term Amazon Bedrock API keys on both the Amazon Bedrock and Mantle endpoints. Each endpoint has its own condition key, so each gets its own statement. The iam:CreateServiceSpecificCredential action also covers service-specific credentials for other services, such as AWS CodeCommit and Amazon Keyspaces (for Apache Cassandra), so confirm that no team depends on them before you attach the policy.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "DenyLongTermKeyCreation", "Effect": "Deny", "Action": [ "iam:CreateAccessKey", "iam:CreateServiceSpecificCredential" ], "Resource": "*" }, { "Sid": "DenyLongTermBedrockKeyUse", "Effect": "Deny", "Action": "bedrock:CallWithBearerToken", "Resource": "*", "Condition": { "StringEquals": { "bedrock:bearerTokenType": "LONG_TERM" } } }, { "Sid": "DenyLongTermMantleKeyUse", "Effect": "Deny", "Action": "bedrock-mantle:CallWithBearerToken", "Resource": "*", "Condition": { "StringEquals": { "bedrock-mantle:bearerTokenType": "LONG_TERM" } } } ] } To create and attach the SCP
- Save the preceding policy as deny-long-term-keys.json.
- Sign in to the AWS CLI with credentials for the management account or your delegated administrator account for policies.
- Enter the following command. Note the policy ID in the output.
# Create the SCP from the policy file you saved in step 1 aws organizations create-policy \ --name DenyLongTermKeys \ --type SERVICE_CONTROL_POLICY \ --description "Deny creation and use of long-term keys" \ --content file://deny-long-term-keys.json - Enter the following command to attach the policy to a test organizational unit (OU). Replace the example IDs with your own.
# Attach the SCP to a test OU before you roll it out more widely aws organizations attach-policy \ --policy-id p-examplepolicyid \ --target-id ou-exampleorgunit - From an account in the test OU, enter aws iam create-access-key --user-name <test-user> and confirm that the request fails with an AccessDenied error.
- After testing, attach the policy to your other OUs.
Some automation might still depend on an access key. You can exempt specific roles with an aws:PrincipalArn condition while you migrate them. SCPs don't apply to the management account, so protect that account separately. For accounts that don't use generative AI at all, add a second SCP that denies bedrock:* and bedrock-mantle:*, so an attacker can't turn on model access there. For more information, refer to Service control policies (SCPs) and Control permissions for generating and using Amazon Bedrock API keys .
Set up spend and activity alerts
Preventive controls reduce risk, but one must include monitoring as well. It shows you normal usage patterns, catches honest mistakes such as an agent running on a more expensive model than intended or stuck in a loop, and detects malicious use of stolen credentials before the bill grows. A cost monitor catches unusual spend, and CloudTrail records the API calls that often come before it.
To create a cost anomaly alert
- Enter the following command to create a monitor for AWS services, and note the MonitorArn in the output. If your account already has an AWS services monitor, use its ARN and skip this step.
- # Create a monitor that tracks spend for each AWS service, including Amazon Bedrock
aws ce create-anomaly-monitor \ --anomaly-monitor '{"MonitorName":"aws-services-monitor","MonitorType":"DIMENSIONAL","MonitorDimension":"SERVICE"}'
- Enter the following command to send a daily email when an anomaly's total impact reaches 100 USD. Replace the ARN, email address, and threshold with your own values.
- # Email a daily summary of anomalies with an impact of 100 USD or more
aws ce create-anomaly-subscription \ --anomaly-subscription '{ "SubscriptionName": "bedrock-spend-alerts", "MonitorArnList": ["arn:aws:ce::111122223333:anomalymonitor/example-monitor-id"], "Subscribers": [{"Type": "EMAIL", "Address": "security-team@example.com"}], "Frequency": "DAILY", "ThresholdExpression": { "Dimensions": { "Key": "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "Values": ["100"], "MatchOptions": ["GREATER_THAN_OR_EQUAL"] } } }'
- Turn on Amazon Bedrock model invocation logging so you have a record of requests in Amazon CloudWatch Logs or Amazon Simple Storage Service (Amazon S3) . For instructions, refer to Monitor model invocation using CloudWatch Logs and Amazon S3 .
Daily summaries go to email. For immediate alerts, use an Amazon Simple Notification Service (Amazon SNS) topic as the subscriber. For more details, refer to Getting started with AWS Cost Anomaly Detection .
Detect rapid changes in token consumption
Cost Anomaly Detection is a daily signal, and billing data can lag by hours. A stolen credential can run up a very large bill at that time. To catch spikes within minutes, measure token consumption per identity from your Amazon Bedrock model invocation logs, and alert when it jumps.
To investigate token usage per identity by the hour
In CloudWatch Logs Insights, select the log group and run the following query. It shows each caller’s token consumption per hour and per model:
filter ispresent(identity.arn) | stats sum(input.inputTokenCount) as input_tokens, sum(output.outputTokenCount) as output_tokens, count(*) as requests by bin(1h) as hour, identity.arn as caller_id, modelId | sort hour desc **
To create a near real-time alert**
- Create a metric filter that turns each log event into a token metric labeled by caller:
aws logs put-metric-filter \ --log-group-name /aws/bedrock/modelinvocations \ --filter-name output-tokens-by-caller \ --filter-pattern '{ $.identity.arn = * }' \ --metric-transformations '[{"metricName": "OutputTokens", "metricNamespace": "BedrockAgents", "metricValue": "$.output.outputTokenCount", "dimensions": { "Caller": "$.identity.arn" }, "unit": "Count"}]' To track input tokens as well, create a second filter for $.input.inputTokenCount.
- Create an alarm that fires when any caller exceeds your expected consumption in a short window. The alarm uses a Metrics Insights query that groups by Caller, so CloudWatch evaluates each caller separately and new callers are covered automatically. Replace the threshold and the SNS topic ARN with your own values:
aws cloudwatch put-metric-alarm \ --alarm-name bedrock-output-token-spike-by-caller \ --comparison-operator GreaterThanThreshold \ --threshold 50000 \ --evaluation-periods 1 \ --treat-missing-data notBreaching \ --alarm-actions arn:aws:sns:us-east-1:<ACCOUNT-ID>:security-alerts \ --metrics '[{ "Id": "q1", "Expression": "SELECT SUM(OutputTokens) FROM SCHEMA(\"BedrockAgents\", Caller) GROUP BY Caller ORDER BY SUM() DESC", "Period": 300, "ReturnData": true }]' Choose the threshold from your own baseline. Run the hourly query for a week or two to see typical usage, then set the threshold comfortably above it. Note that the query above sums up tokens over 5 minutes ("Period": 300), while the Logs Insights query reports per hour, so divide your hourly baseline accordingly. Make sure to add an action to the alarm ranging from recieving a notification to removing bedrock permission altogether.
Keep these points in mind:
- Each distinct Caller value creates its own custom metric, which adds cost. This is usually acceptable for a bounded set of developer and role identities.
- A 5-minute window detects a spike in about 5 to 10 minutes. A daily bill would show the same spike up to a day later.
GuardDuty AI Protection
If you use GuardDuty, turn on GuardDuty AI Protection. It builds a baseline of model invocation activity for each identity and account, and it generates Impact:IAMUser/AnomalousModelInvocation and Impact:IAMUser/CostHarvesting findings when activity deviates from that baseline, such as calls from an unfamiliar IP address or unusual token volumes. AI Protection charges for the CloudTrail data events that it analyzes. For more information, refer to GuardDuty AI Protection .
Create EventBridge rules that match these CloudTrail events when they don't come from your infrastructure as code pipelines:
-
PutUseCaseForModelAccessandCreateFoundationModelAgreement, which unlock models in an account.
-
PutModelInvocationLoggingConfigurationandDeleteModelInvocationLoggingConfiguration, which change what gets logged.
-
CreateUserandCreateAccessKey, which can signal an attacker setting up persistent access.
The following event pattern matches the Amazon Bedrock events. Replace the role ARN with the role that your pipeline uses, and add an Amazon SNS topic as the rule target.
{ "source": ["aws.bedrock"], "detail-type": ["AWS API Call via CloudTrail"], "detail": { "eventName": [ "PutUseCaseForModelAccess", "CreateFoundationModelAgreement", "PutModelInvocationLoggingConfiguration", "DeleteModelInvocationLoggingConfiguration" ], "userIdentity": { "arn": [{ "anything-but": { "prefix": "arn:aws:sts::111122223333:assumed-role/PipelineDeployRole/" } }] } } } Create this rule in each account and Region where developers use Amazon Bedrock, or forward the events to a central event bus. IAM is a global service, so IAM events such as CreateUser and CreateAccessKey arrive only in US East (N. Virginia). Create a second rule in that Region with "source": ["aws.iam"] and those two event names. For instructions, refer to Creating rules using the Enhanced Builder . For more information about the events, refer to Monitor Amazon Bedrock API calls using CloudTrail .
Also watch for bursts of InvokeModel calls with low token counts in your model invocation logs or in the InputTokenCount and OutputTokenCount metrics in Amazon CloudWatch. Small requests like these can be a sign that someone is testing stolen credentials. For more information, refer to Monitor bedrock-runtime inference using CloudWatch metrics .
Clean up
The resources in this post are security controls, and you should keep them in production. If you created them in a test environment, remove them in this order:
- Delete the anomaly subscription and monitor with aws ce delete-anomaly-subscription and aws ce delete-anomaly-monitor.
- Delete the EventBridge rules. If you turned on GuardDuty AI Protection only for testing, turn it off to stop its charges.
- Turn off model invocation logging in the Amazon Bedrock console, and delete the log data in CloudWatch Logs or Amazon S3 to stop storage charges.
- Detach the SCP with aws organizations detach-policy, and then delete it with aws organizations delete-policy.
- Remove the BedrockAgentAccess account assignments in IAM Identity Center, and then delete the permission set.
- Remove the bedrock-agent profile from ~/.aws/config the settings from ~/.claude/settings.json, and the permission profile from ~/.codex/config.toml on test workstations.
You pay for the model usage your agents generate at Amazon Bedrock rates. For details, refer to Amazon Bedrock pricing .
Conclusion
We showed how to reduce the risk of credential theft for AI coding agents on Amazon Bedrock. Developers sign in through IAM Identity Center and get credentials that expire. The agent runs with a role that can invoke approved models and look up inference profiles, an SCP blocks long-term keys across your organization, and CloudWatch alerts help you detect unusual spend and configuration changes.
As a next step, apply the credential source from the solution overview table that matches each place your agents run, including CI pipelines and cloud development environments. To track spend per team, refer to Create an application inference profile . For more guidance on Amazon Bedrock API keys, read Securing Amazon Bedrock API keys: Best practices for implementation and management on the AWS Security Blog.
If you have questions about securing generative AI workloads on AWS, contact an AWS Representative .
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article