# How to protect exchange API keys from an AI agent: isolation, scopes, and rotation

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-zashchitit-api-klyuchi-birzhi-ot-ii-agenta_en.html

## Guide passport
![Illustration: Guide passport](https://ai-release.org/guides/img/kak-zashchitit-api-klyuchi-birzhi-ot-ii-agenta-en-1.jpg?v=1795308306)


- **Time:** 20–40 minutes
- **Stack:** any trading bot or AI agent, an exchange with subaccounts, Docker, systemd, a secret manager
- **Level:** Intermediate
- **What you get:** a key that cannot be turned into a withdrawal, a secret isolated from the model, restricted network egress, rotation, and a ready incident runbook

An exchange API key is not a forum password. If it leaks, the damage is measured in order history and balance, not in a password reset. This guide is about reducing the cost of a leak to near zero before it happens.

## How an exchange key differs from an LLM key

An LLM key spends tokens. An exchange key moves money. The permission model defines everything:

| Permission | LLM key | Exchange key |
|---|---|---|
| Read data | yes | yes |
| Create operations | generate text | real-money orders |
| Withdraw funds | no | **often enabled by default** |
| Cost of a leak | a token bill | the subaccount balance |

So the defense is not “hide the string”. It is **shrinking the permission set**. Even a stolen key without withdrawal rights and with an IP allowlist is a bounded problem, not a lost deposit.

## Threat model: how keys leak in 2026

- **Bot infrastructure compromise.** The Bloom Telegram bot stored users’ private keys and drained 48 wallets of about $953,000 in 94 seconds. The cause was not a model hack but an architecture where keys were reachable by the service.
- **Exposed agent platforms.** In February 2026 researchers found more than 40,000 internet-reachable OpenClaw instances. A public interface plus weak authentication makes keys reachable from outside.
- **Prompt injection.** An agent reads external text, treats it as a command, and calls a tool it should never have called. If that tool holds a key with withdrawal rights, the injection becomes a theft.

The lesson: the threat is almost never clever cryptography. It is the permissions you granted and the channels through which the secret is reachable.

## Step 1. Create a key with the minimum scope

Where the exchange supports it, create a **subaccount** and a separate key for trading only.

- Read balance and positions — yes.
- Create and cancel orders — yes.
- **Withdraw funds — no.** Disable it at the key level where possible.
- IP allowlist — only the executor’s address.
- Symbol and max-order restrictions where the exchange offers them.
- A separate key per agent or service, so rotating one does not break the others.

```text
subaccount: agent-hot-01
key label:  executor-01
scopes:     read, trade
withdraw:   disabled
ip allow:   203.0.113.10
symbols:    BTC/USDC, ETH/USDC
```

**Why it matters:** if the key leaks, the attacker cannot withdraw. The worst case is a trading loss bounded by your limits. Painful, but survivable.

## Step 2. Isolate the secret from the agent

The core rule: **the key never enters the model context, the logs, or tool responses**. A model can ask to “show the config”, and if the key sits in a file the agent can read, it ends up in chat or history.

- Store the key in a secret manager or a `chmod 600` file readable only by the executor process.
- Pass it through the process environment, never through the prompt.
- Run the analyst in a container **without** access to key paths.
- Redact secrets in logs: `sk-...abcd`, not the full string.
- Deny the agent access to `.env` and config directories.

```python
import os, re

KEY = os.environ["EXCHANGE_TRADE_KEY"]  # executor only

def redact(text: str) -> str:
    # keep the key out of logs and model responses
    return re.sub(r"(?i)(api[_-]?key|secret|token)(\s*[:=]\s*)\S+", r"\1\2***", text or "")
```

**Why it matters:** even if the model errs and tries to print the config, it will not see the key. The secret lives in the executor process, not in shared context.

## Step 3. Restrict network and processes
![Illustration: Step 3. Restrict network and processes](https://ai-release.org/guides/img/kak-zashchitit-api-klyuchi-birzhi-ot-ii-agenta-en-2.jpg?v=1795308311)


Secret isolation is useless if the agent container can reach the whole server and every domain.

- Run the analyst and the executor in separate containers.
- Allow the executor egress only to the exchange API.
- Allow the analyst egress only to the data sources it needs.
- Keep administrative interfaces off the public network: no “just in case” open panels.
- Do not mount the Docker socket or your home directory into the agent container.

```yaml
# docker-compose.yml (excerpt)
services:
  executor:
    build: ./executor
    env_file: ./secrets/executor.env      # chmod 600, not in git
    read_only: true
    networks: [exchange_net]
    # no docker.sock, no home directories
  analyst:
    build: ./analyst
    networks: [data_net]
    # no exchange keys here at all

networks:
  exchange_net: {}
  data_net: {}
```

**Why it matters:** a compromised analyst cannot reach the key and cannot reach the exchange directly. It can only produce proposals that the controller checks.

## Step 4. Set up rotation and monitoring

A key with no expiry is a key forever. Make rotation routine, not a reaction to an incident.

- Keep **two active keys**: current and next. To rotate, create the new one, switch, revoke the old one.
- Rotate on a schedule (for example every 30–90 days) and on any suspicion.
- Alert on failed authentication, new IPs, and spikes in order cancellations.
- Keep a log: when the key was created, where it is used, when it was rotated.
- Verify that a revoked key really returns an authorization error.

```bash
# quick check that the old key is dead
curl -s -H "X-API-KEY: $OLD_KEY" https://api.exchange.example/account | head
# expected: 401 / invalid key
```

**Why it matters:** rotation limits the window in which a leaked key is useful. Monitoring catches the leak before the balance does.

## Step 5. Runbook: what to do on a leak

Act in order, and do not rely on the model.

1. **Revoke the key** in the exchange panel — immediately, not “after the review”.
2. **Stop the executor** with an independent kill switch.
3. **Check history**: orders, cancellations, withdrawal attempts, new IPs.
4. **Assess the damage** from actual operations, not from the agent’s logs.
5. **Rotate the remaining keys** if they could have been exposed too.
6. **Check the infrastructure**: open ports, admin panels, container access.
7. **Write the postmortem**: how the key became reachable and what now closes it.

If the key had withdrawal rights, treat the funds as lost until proven otherwise and act as during an incident, not a suspicion.

## Checklist

- ☐ A dedicated subaccount for the agent
- ☐ A key without withdrawal rights
- ☐ An IP allowlist for the executor only
- ☐ A separate key per service
- ☐ The key is not in the prompt, logs, or tool responses
- ☐ The analyst cannot access key files
- ☐ Egress limited to the exchange API
- ☐ No open admin panels or Docker socket in the agent container
- ☐ Scheduled rotation and two active keys
- ☐ Alerts on failed auth and new IPs
- ☐ An independent kill switch
- ☐ A tested leak runbook

## Troubleshooting

**The bot stopped trading after enabling the IP allowlist.** The executor goes out through a different egress IP (VPN, NAT, a second server). Fix: find the actual outbound IP and add it, do not disable the allowlist.

**The key shows up in application logs.** The cause is logging environment variables or full API responses. Fix: apply `redact()` on every logging path and check that `.env` does not appear in `docker inspect` or error reports.

**Some services broke after rotation.** They all shared one key. Fix: issue a separate key per service from the start and rotate them one by one.

**The agent “sees” the key in its context.** The key sits in a file the agent’s tool can read, or in the system prompt. Fix: remove the key from reachable paths and from the prompt, and keep it only in the executor process.

## FAQ

**Is disabling withdrawals enough?** It is the most important step, but not the only one. Without an IP allowlist and secret isolation, the key can still be used for losing trades or balance reconnaissance.

**Can I keep the key in an environment variable?** Yes, if only the executor can read that environment. But do not pass it to the agent, do not log it, and do not commit it to git.

**Do I need a separate key if there is only one agent?** Yes. A per-service key simplifies rotation and limits the blast radius: revoking one does not stop everything.

**What matters more: rotation or the allowlist?** Both. The allowlist narrows the source, rotation shortens the lifetime of a leaked key. Each is weaker alone.

## Further reading
![Illustration: Further reading](https://ai-release.org/guides/img/kak-zashchitit-api-klyuchi-birzhi-ot-ii-agenta-en-3.jpg?v=1795308315)


- [A safe AI trader: architecture, limits, and prompt-injection defense](https://ai-release.org/guides/bezopasnyy-ii-treyding-arhitektura-i-limity_en.html)
- [How to store API keys for LLM services safely](https://ai-release.org/guides/kak-bezopasno-hranit-api-klyuchi-dlya-llm-servisov-env.html) (RU)
- [How to run an AI agent in Docker: isolation and permissions](https://ai-release.org/guides/kak-zapustit-ii-agenta-v-docker-izolyatsiya-prava-dostu.html) (RU)
- [How to set spending limits and budgets for AI agents](https://ai-release.org/guides/kak-nastroit-limity-rashodov-i-byudzhety-dlya-ii-agento.html) (RU)
