Sub topic 8
Scoped, short-lived, per-user credentials
This chapter assumes you know how LLM tool calling works, what an API token or an IAM role is, and how to read short Python and JSON snippets. Earlier chapters covered tool allowlists and authorization checks in code. This chapter covers the credentials those tools use to reach other systems.
Why credentials are the last line of defense
Allowlists and argument checks run in your runtime. They can have bugs, and a tool can be added without a check. The credential a tool presents to a database, bucket, or SaaS API is a second, independent limit. If the credential cannot do something, the call fails even when your code and the model both get it wrong.
A single shared service account for the whole agent works against this. It must be powerful enough for every task and every user, so any injected instruction inherits all of that power. A good agent credential has three properties:
| Property | Question it answers | Failure it prevents |
|---|---|---|
| Scoped | Which actions on which resources? | A read tool that can also delete or write |
| Short-lived | For how long is it valid? | A leaked token that stays useful for months |
| Per-user | On whose behalf does it act? | One user's request reading another user's data |
Scoped: narrow the actions and the resources
A scope has two parts: the actions allowed and the resources they apply to. Most overly broad credentials get the first part right and the second part wrong. s3:GetObject on * is a read-only permission, but it reads every bucket the account can reach.
Here is the policy from the earlier example. It allows one action on one prefix of one bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-reports-bucket/public-summaries/*"
}
]
}Notice what this policy leaves out. There is no s3:ListBucket, so the agent cannot enumerate other keys. There is no s3:PutObject, so injected text cannot make the agent plant files. Add each action only when a specific tool needs it, and record which tool needs it.
Scope applies outside AWS too:
- Database: create a role with
SELECTon the specific tables or views the task needs, not the application's owner role. A view that omits sensitive columns is a cheap way to scope columns. - Third-party APIs: request the narrowest OAuth scopes (for example, read-only calendar access instead of full account access). Many providers offer fine-grained tokens limited to one repository or project.
- Internal services: issue a token with an audience and a scope claim, and have the service check both.
Use separate credentials for separate tools. A read_file tool and a send_email tool should not share an identity. If they do, compromising one tool's path gives access to the other tool's resources.
Short-lived: make expiry the default
A long-lived key is a standing risk. It shows up in logs, tool output, traces, and prompts, and anything the model sees can end up in its output. A credential that expires in 15 minutes limits how long a leak stays useful.
Prefer credentials that are issued on demand and expire on their own:
- AWS STS
AssumeRolereturns an access key, secret, and session token that expire after a set duration (minimum 900 seconds). - Cloud workload identity (for example, IAM roles for service accounts, or managed identities) avoids storing keys at all.
- OAuth access tokens are short-lived by design. Keep the refresh token in your runtime's secret store and never expose it to the tool code the model controls.
Tie the lifetime to the task, not to the process. A task that takes two minutes should get a credential that lasts a few minutes. Mint it when the task starts and let it lapse when the task ends.
Per-user: act with the requester's authority
The confused deputy problem from the threat-model chapter applies directly. If the agent uses one powerful identity, a request from user A can return user B's data, because the backend sees only the agent. The fix is to make the backend see the user.
There are two common designs:
- Token exchange or delegation. The agent's runtime exchanges the user's session for a credential limited to that user and that task. The backend enforces the user's own permissions.
- Per-user resource scoping. The runtime mints a credential whose resource scope contains the user's identifier, such as a key prefix
users/<user_id>/.
In both designs the user identity comes from your authenticated session, never from the model's output. If the model supplies user_id as a tool argument, an injected instruction can change it.
Worked example: a per-user, per-task AWS credential
The function below uses an AWS session policy. A session policy is an extra policy passed to AssumeRole. The resulting permissions are the intersection of the role's policy and the session policy. The role can therefore be reasonably broad, while each session is narrow.
import json
import re
import boto3
sts = boto3.client("sts")
ROLE_ARN = "arn:aws:iam::123456789012:role/agent-report-reader"
BUCKET = "example-reports-bucket"
USER_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
def credentials_for_task(user_id: str, task_id: str) -> dict:
"""Mint a 15-minute credential limited to one user's report prefix."""
# user_id must come from the authenticated session, not from the model.
if not USER_ID_PATTERN.fullmatch(user_id):
raise ValueError("invalid user id")
if not USER_ID_PATTERN.fullmatch(task_id):
raise ValueError("invalid task id")
session_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": f"arn:aws:s3:::{BUCKET}/users/{user_id}/*",
}
],
}
response = sts.assume_role(
RoleArn=ROLE_ARN,
RoleSessionName=f"agent-{user_id}-{task_id}"[:64],
Policy=json.dumps(session_policy),
DurationSeconds=900,
)
return response["Credentials"]
def read_report(creds: dict, user_id: str, name: str) -> bytes:
"""Tool body: reads one report using the scoped credential."""
s3 = boto3.client(
"s3",
aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"],
)
key = f"users/{user_id}/{name}"
return s3.get_object(Bucket=BUCKET, Key=key)["Body"].read()Three details matter here:
- The ID pattern check rejects
*,/, and... Without it, a crafteduser_idsuch as*would widen the resource ARN in the session policy. RoleSessionNamerecords the user and task in CloudTrail, so each call is attributable. Session names accept only letters, digits, and+=,.@_-, which the pattern also guarantees.- Even if
read_reporthas a path bug and requestsusers/other-user/secret.txt, S3 returnsAccessDenied. The credential enforces the limit.
The credential object itself should stay inside the runtime. Pass the tool a client or a closure, not the raw secret in a value the model can read back.
How the flow fits together
Common errors
- Putting secrets in the prompt or tool results. Anything the model sees can be echoed back, logged, or sent through an outbound tool. Keep credentials in the runtime and attach them when the tool executes.
- Letting the model pick the identity. Arguments such as
user_id,tenant, orrolemust be derived from the session. Treat them like any other untrusted value. - Over-long lifetimes. Setting 12 hours "so tasks don't fail" recreates a standing key. Handle expiry by minting a new credential, and size the duration to the task.
- Scoping actions but not resources.
s3:*on one bucket orGetObjecton*are both too wide. Check both fields. - Caching across users. A credential cache keyed only by task type serves user A's credential to user B. Key the cache by user and task, or skip caching.
- Trusting the role alone. If the base role is broad and you forget the session policy, every session gets the broad permissions. Test that out-of-scope calls fail.
Checking that it works
Scoping is only real if you have seen a call fail. For each credential you design, write two tests: one in-scope call that succeeds and one out-of-scope call that raises AccessDenied (or the equivalent). Run the out-of-scope test with the same credential in the same session. Also test that an expired credential is rejected, using a short duration in a test environment.
Exercise
An agent answers questions about a customer's invoices. A developer gives it one long-lived service-account key that can read the invoices table for all customers, and passes customer_id as a tool argument chosen by the model. Name two problems and give one fix for each.
Show answer
First, the key is long-lived and unscoped by customer, so a leak or an injected instruction exposes every customer's invoices for as long as the key is valid. Fix: mint a short-lived credential (for example 15 minutes) per task, limited to the customer's rows or prefix. Second, the model chooses customer_id, so an injected instruction can request another customer's data and the all-customers key will allow it. Fix: take the customer identity from the authenticated session in the runtime, and use it to scope the credential, so the backend refuses other customers' data even if the model asks for it.
Exercise
In the credentials_for_task example, what could go wrong if the USER_ID_PATTERN check were removed and user_id were "*"?
Show answer
The session policy resource would become arn:aws:s3:::example-reports-bucket/users/*/*, which matches every user's reports. The credential would no longer be per-user, and the agent could read any user's files. The pattern check rejects characters such as *, /, and ., so the resource stays limited to a single user's prefix.