Sub topic 8
Limiting the damage with scoped, short-lived credentials
This chapter assumes you can use Git and a command line, and that you know what an API key is. It also assumes you can set environment variables. The previous chapter moved secrets out of source code. This chapter covers the next question: if a credential still leaks, how much can an attacker do with it, and for how long?
Why scope and lifetime matter
Every control from earlier chapters can fail. An ignore file may not cover a path. A log may echo a token. An agent may read an environment variable. A credential's power and lifetime decide the cost of that failure.
Two properties limit the damage:
- Scope is what a credential is allowed to do. A key that can only read one storage bucket is narrower than a key that administers the whole account.
- Lifetime is how long a credential works. A token that expires in 15 minutes is useless to an attacker an hour later. A key with no expiry stays useful until someone revokes it.
The principle of least privilege says each credential should have the smallest scope and shortest lifetime that still lets the task finish. Applied to AI tools, this means the credential an assistant or agent can reach should never be your personal admin login.
Scoping a credential
Scoping works along several dimensions. Check each one when you create a key.
| Dimension | Question to ask | Example of a narrow choice |
|---|---|---|
| Actions | Which operations are allowed? | Read-only, not read and write |
| Resources | Which objects can it touch? | One bucket or one repository |
| Environment | Which system does it belong to? | A staging key, not production |
| Network | Where can it be used from? | A fixed IP range |
| Identity | Who or what owns it? | A service account for one job |
Use a separate credential per purpose
Give each tool, project, and environment its own credential. Then a leak from one assistant session affects one project, and revoking the key does not break everything else. Shared keys also make auditing hard, because logs cannot tell you which tool made a request.
A practical naming habit helps: include the owner, purpose, and environment in the key name, such as ai-assistant-docs-staging. During an incident you can find and revoke the right key quickly.
Prefer read-only by default
An assistant that explores a codebase or reads data rarely needs write access. Start with read-only and add write permission only for the specific action that needs it. Many mistakes by agents, such as a deleted table or an overwritten file, become impossible when the credential cannot write.
Keep production out of reach
Give development tools development credentials. If an agent needs to test an integration, point it at a sandbox account or a staging database with fake data. A leaked staging key exposes test data. A leaked production key exposes customers.
An example of a narrow cloud policy
Cloud providers let you write a policy that limits a role to exact actions on exact resources. This AWS IAM policy allows reading objects from a single folder of a single bucket and nothing else.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::example-docs-bucket/public-docs/*"
}
]
}Compare this with a policy that allows "Action": "*" on "Resource": "*". The first policy lets a leaked key download files from one folder. The second lets it create servers, read every database, and delete backups. Wildcards in policies are a common source of oversized credentials, so treat each * as something to justify.
Short-lived credentials
Scope limits what an attacker can do. Lifetime limits when they can do it. The best pattern is to avoid long-lived keys entirely and issue temporary credentials on demand.
How temporary credentials work
With temporary credentials, you authenticate once with a strong method such as single sign-on, and a service issues a token that expires after a set time. Your tools use that token. When it expires, they request another.
Common mechanisms include:
- AWS STS, which issues temporary access keys, usually from an assumed role.
- Cloud SSO sessions, which you refresh with a login command.
- OIDC federation, where a CI job proves its identity to the cloud provider and receives a token, so you store no key in CI at all.
- Short-lived tokens from a secrets manager, such as dynamic database credentials that the manager creates and deletes automatically.
Example: assume a role for one session
This command requests temporary credentials for a narrow role and limits them to 15 minutes, the minimum duration AWS allows. Replace the account number and role name with your own.
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/ai-assistant-readonly \
--role-session-name ai-session \
--duration-seconds 900The output contains an access key ID, a secret access key, and a session token. Set all three as environment variables for the session. The session token is required, and the credentials stop working when the duration ends.
A short Python script can read the response and print the export lines. It parses JSON from the command and avoids writing the credentials to a file.
import json
import subprocess
result = subprocess.run(
[
"aws", "sts", "assume-role",
"--role-arn", "arn:aws:iam::123456789012:role/ai-assistant-readonly",
"--role-session-name", "ai-session",
"--duration-seconds", "900",
],
capture_output=True,
text=True,
check=True,
)
creds = json.loads(result.stdout)["Credentials"]
print(f"export AWS_ACCESS_KEY_ID={creds['AccessKeyId']}")
print(f"export AWS_SECRET_ACCESS_KEY={creds['SecretAccessKey']}")
print(f"export AWS_SESSION_TOKEN={creds['SessionToken']}")Run it inside a subshell, for example eval "$(python assume.py)" in the terminal where you launch the tool. Do not let the output land in a shell history file, a shared log, or an AI chat.
Trade-offs of short lifetimes
Short lifetimes add friction. Sessions expire in the middle of long tasks, and you must refresh them. Choose a duration that matches the task. One hour is a reasonable starting point for interactive work. For a long-running agent, prefer a mechanism that refreshes tokens automatically over a single long-lived key.
Common errors
- Reusing your personal credentials. Your login usually carries every permission you hold. Create a dedicated role or service account for the tool.
- Scoping the action but not the resource. Allowing
s3:GetObjecton every bucket is still broad. - Treating expiry as a substitute for scope. A 12-hour admin token is still dangerous for 12 hours.
- Forgetting the session token. Temporary AWS credentials fail with an authentication error if you set only the key ID and secret.
- Storing temporary credentials in a file. Cached tokens on disk, such as in a home-directory config folder, are readable by any agent with file access. Check what your agent's file permissions allow.
- Never testing the limits. Try an action the credential should not allow. If it succeeds, the scope is wrong.
Checking what a credential can do
Verify scope instead of assuming it. Confirm the identity first.
aws sts get-caller-identityThis prints the account and the role in use. If it shows your personal user instead of the tool's role, the wrong credentials are active. Then run a forbidden action, such as listing a bucket the role should not see, and confirm it returns an access denied error.
Most providers also offer tools that report unused permissions. Review them periodically and remove permissions that were never used.
Connecting to incident response
Narrow, short-lived credentials make the response to a leak simpler. If a token expires in an hour, rotation may be automatic. If a key is scoped to one project, revoking it affects only that project. The incident response chapter builds on this: you will revoke, rotate, and review, and the work is smaller when each credential was limited from the start.
Exercise
A teammate wants an AI agent to summarize the contents of one S3 bucket named reports-staging. They plan to export their own administrator access keys, which never expire. Describe two changes that reduce the risk, one for scope and one for lifetime.
Show answer
For scope, create a dedicated role for the agent whose policy allows only s3:GetObject and s3:ListBucket on reports-staging, with no write or wildcard permissions. For lifetime, have the agent use temporary credentials from aws sts assume-role or an SSO session with a short duration, such as one hour, so a leaked token expires soon. The agent then never holds the administrator keys.
Exercise
You run aws sts get-caller-identity before starting an agent and see your personal IAM user instead of the ai-assistant-readonly role. What does this tell you, and what should you do before launching the tool?
Show answer
It shows the shell still has your personal credentials, so the agent would act with all of your permissions. Stop, clear or replace the personal credentials in the environment, assume the narrow role, set the access key, secret, and session token, and run get-caller-identity again to confirm the role before launching the tool.