Sub topic 10
Separate keys, permissions, and spend limits
This chapter assumes you can set environment variables, read short Python or JavaScript snippets, and have created at least one API key in a provider console. Earlier chapters showed how to keep a key out of your code. This chapter covers how to limit the damage if a key leaks anyway.
Why one key is not enough
A single key used everywhere has a large blast radius. If it leaks from a laptop, a log file, or a CI run, the attacker gets everything that key can do. You also can't revoke it without breaking every system that uses it.
The fix is to make each key small in three ways:
- Scope: each key is used by one thing only.
- Permissions: each key can do only what that thing needs.
- Spend: each key, or the project that owns it, has a cap on cost.
None of these stop a leak. They limit what a leaked key is worth and make revocation cheap.
Use a separate key for each purpose
Create a new key for each environment and each service. A reasonable starting split looks like this:
| Key | Used by | Typical limit |
|---|---|---|
| `dev-alice-laptop` | One developer's machine | Small monthly budget |
| `ci-tests` | The CI test job | Very small budget, cheap model only |
| `prod-chat-backend` | The deployed backend service | Monthly cap with alerts |
| `staging-chat-backend` | The staging deployment | Small budget |
Name keys so that a leaked key tells you where to look. Most consoles let you set a name or description when you create the key. A key called key1 gives you nothing during an incident. A key called ci-tests tells you which pipeline to check and which secret to replace.
What separation gives you
- Targeted revocation. If
dev-alice-laptopleaks, you revoke it. Production keeps running. - Attribution. Usage dashboards show which key made which requests, so you can see which one is spending money.
- Different risk levels. A developer laptop is more likely to be lost or compromised than a locked-down production host. It should not hold the production key.
- Safe offboarding. When someone leaves, you revoke their personal key. You don't rotate everything.
Don't share keys between people
Shared keys hide who did what and make revocation disruptive. Give each developer their own key. If your provider supports it, tie keys to individual users or service accounts instead of one shared account.
Permissions: give each key the least access it needs
The principle of least privilege means a credential should be able to do only what its job requires. What you can restrict depends on the provider. Common options include:
- Project or workspace scoping. The key works only inside one project, so its usage and billing are separate from your other projects.
- Endpoint or capability restrictions. The key can call only certain APIs, for example chat completions but not file uploads, fine-tuning, or account management.
- Read-only versus read-write. Some providers let you create keys that can read resources but not create or delete them.
- Model allow-lists. The key can use only specific models, which stops a leaked key from calling the most expensive one.
- IP or network restrictions. The key works only from certain addresses. This helps for servers with fixed IPs, though it is awkward for laptops and many CI runners.
Providers differ a lot here. Some offer fine-grained permissions, and others offer little beyond project separation. Check your provider's console and documentation for what exists. Don't assume a restriction exists because the option sounds standard.
If your provider offers only coarse permissions, project separation is still useful. A separate project per environment gives you separate keys, usage, and budgets even without fine-grained scopes.
Admin keys are a different class
Some providers have separate administrative keys that can create and delete other keys or change billing. Treat these as more sensitive than ordinary inference keys. Don't put them in application code, CI, or a .env file used by your app. Use them only from a trusted place, and only when you are managing keys.
Spend limits
A leaked LLM key is a direct financial risk. Attackers use stolen keys to run their own workloads, and a busy key can spend a lot of money in hours. A bug in your own code, such as a retry loop or an unbounded agent, can do the same thing without any attacker.
There are two kinds of control, and they behave differently.
| Control | What it does | Limitation |
|---|---|---|
| Hard limit (budget cap) | Blocks requests once spend reaches a threshold | May apply per project or account, not per key. Enforcement can lag behind real usage. |
| Alert (soft limit) | Sends a notification at a threshold | Does nothing by itself. Someone must read it and act. |
Use both. Set alerts at lower thresholds, such as 50% and 80% of budget, so you hear about unusual spending early. Set a hard cap at the highest amount you could tolerate losing.
Gotchas with spend limits
- Usage reporting is delayed. Billing data often arrives minutes to hours late. A fast attack can pass your cap before it takes effect. The cap is a backstop, not a guarantee.
- Limits may be per project or per account. If your provider only caps at the account level, one noisy key can use the budget for everything. That is another reason to use separate projects.
- A hard cap causes an outage. When production hits its cap, requests fail. Decide in advance what your application does then. Failing with a clear error is better than retrying forever.
- Rate limits are not spend limits. A requests-per-minute limit slows usage but doesn't bound total cost over a month. Some providers also let you set a lower rate limit on a key or project, which does help.
- Prepaid credit is a natural cap. If your provider supports prepaid balances without auto-reload, a leaked key can spend only what is in the account. Turning off auto-recharge is a simple safety measure.
Limit spending in your own code too
Provider limits are the last line of defense. You can add a cheap application-level check in front of them. This example caps the output size of each request and counts calls per process. Treat it as a guard against your own bugs, not against an attacker who holds the key.
import os
import requests
MAX_CALLS = 100
MAX_OUTPUT_TOKENS = 500
_calls = 0
def ask(prompt: str) -> dict:
global _calls
if _calls >= MAX_CALLS:
raise RuntimeError("Call budget for this process is used up")
_calls += 1
response = requests.post(
"https://api.example.com/v1/chat", # placeholder URL: use your provider's endpoint
headers={"Authorization": f"Bearer {os.environ['LLM_API_KEY']}"},
json={"prompt": prompt, "max_tokens": MAX_OUTPUT_TOKENS},
timeout=30,
)
response.raise_for_status()
return response.json()The parameter name for the output limit varies by provider, so check your provider's documentation for the exact field.
Matching keys to environments in practice
Keep each key in the place that matches its purpose, and use the same variable name everywhere so your code doesn't change.
# Developer laptop: .env (git-ignored) holds the personal dev key
LLM_API_KEY=dev-key-for-this-developerjobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
run: ./run_tests.sh
env:
LLM_API_KEY: ${{ secrets.LLM_API_KEY_CI }}In production, the deployment platform injects the production key as LLM_API_KEY. The code reads the same variable in all three places and gets a different key with different limits each time.
Review and cleanup
Separate keys only help if you keep track of them. Build these habits:
- Keep a short inventory: key name, owner, purpose, where it is stored, and creation date.
- Check the provider's usage dashboard regularly. Look for keys that are used more than expected or at odd hours.
- Delete keys that are no longer used. An unused key is risk with no benefit.
- Revisit budgets when usage changes, so caps neither block normal traffic nor sit far above real needs.
Common mistakes
- One key for everything. Revoking it breaks every system at once, so people hesitate to revoke it during an incident.
- No budget on test or CI keys. These are often the least protected, and a runaway test can still spend real money.
- Alerts with no owner. An alert sent to an unread inbox is the same as no alert.
- Assuming a cap is instant. Plan for some overshoot.
- Giving admin keys to applications. An app only needs inference access.
Exercise
Your team has one LLM API key shared by developers, the CI pipeline, and the production backend. List three concrete changes that reduce the damage if that key leaks, and name one limitation of the spend cap you set.
Show answer
Any three of these: create a separate key per developer, one for CI, and one for production; place environments in separate projects so each has its own usage and budget; give CI and development keys small budgets and restrict them to cheap models or needed endpoints if the provider allows it; name keys by purpose so a leak is easy to trace; set alerts at lower thresholds plus a hard cap; keep admin keys out of application environments. Limitations of a spend cap: usage reporting can be delayed so spending may overshoot the cap, the cap may apply per project or account instead of per key, and hitting the cap on production causes failed requests, so the application needs a plan for that case.
Exercise
Why is a rate limit not a substitute for a spend limit?
Show answer
A rate limit controls how fast requests can be made, not how much total money is spent. A key limited to a fixed number of requests per minute can still run continuously for weeks and accumulate a large bill. A spend limit bounds total cost over a billing period.