Crowork Book a free audit

How AI agents should store your API keys

How AI agents mishandle provider API keys, what encrypted storage and rotation look like, and the two key models, your own keys or managed ones, that we run in production.

Most production AI agent deployments have a secrets problem nobody has looked at closely. The .env file sits on a VPS with 640 permissions and a shared ubuntu login. The database row that holds the user's OpenAI key is a TEXT column with no encryption at the application level. The developer knows the key is "just a string", so it gets treated like any other user input, until the day a model-provider breach or a misconfigured S3 bucket dumps the database and the string becomes a runaway bill in the thousands.

This post covers the failure modes we see most often, what good key handling looks like from an engineering standpoint, and the two deployment models we offer, BYOK (bring your own key) and managed provisioning, with the reason each one exists.

The plaintext trap

The attack surface for a plaintext key is larger than most teams realise. A key in an .env file is readable by any process on that machine under the same user, any crash reporter that captures environment variables, any log aggregator that prints process.env on startup, and any shell command substitution that expands the variable into a log line by accident. That is before you consider shared hosting, noisy neighbours, or a developer's laptop that also runs the staging environment.

A key in a database TEXT column is in every database backup, and backups often sit in a different bucket with looser IAM policies because "they're just backups". It is in every SELECT * run by an admin tool, every ORM debug log that prints full query results, and every database snapshot replicated to a read replica for analytics.

None of this needs a sophisticated attacker. Most plaintext key exposures are boring: a misconfigured environment, a developer checking the wrong file into git, a backup restore test that left credentials in a staging database nobody cleaned up.

What good handling looks like

No single technique handles this. It takes four properties working together:

  • Encrypted at rest, at the application layer. The key is encrypted with a data encryption key (DEK) before it ever touches the database. The DEK itself is wrapped by a key encryption key (KEK) held in a secrets manager: Fly.io secrets, Supabase Vault, or a dedicated KMS. The database stores ciphertext, so even a full backup dump is useless without the KEK.
  • Scoped, not root. Store the narrowest key the integration needs. An agent that only reads files does not need write access, and an agent scoped to one project does not get an org-level key. When the blast radius of a compromise is bounded by scope, rotation costs less too.
  • Revocable without downtime. You need a path to invalidate a key and rotate in a replacement without taking the agent offline. That is why key storage is a separate concern from agent configuration: the agent holds a reference to the key record, not the key bytes.
  • EU-resident infrastructure. For teams under GDPR or with EU customers, the credential store itself needs to be physically in the region. We run agent infrastructure on Fly.io (Amsterdam/Frankfurt) with Supabase in the EU-West region. Where the store sits changes which court orders can reach your data and which legal exposure you carry.

If you are not doing all four, you have a real gap, and most stacks we see do two of them, sometimes three.

The Supabase Vault pattern in practice

Supabase Vault wraps PostgreSQL with a pgsodium-backed secrets table. The key bytes never appear in a normal SELECT. An agent that needs to make an authenticated call does this:

-- store (write-once at onboarding)
SELECT vault.create_secret(
  :plaintext_key,
  'openai_key_user_abc',
  'OpenAI key for user abc'
);

-- retrieve at call time (server-side only, never exposed to client)
SELECT decrypted_secret
FROM  vault.decrypted_secrets
WHERE name = 'openai_key_user_abc';

The decrypted_secrets view is a server-side function call rather than a real table. Row-level security on that view means a Supabase service-role key can read it and an anon or public key cannot. The plaintext never leaves the Postgres process boundary in cleartext, and a database backup holds only the ciphertext column, without the pgsodium master key held at the infrastructure level.

Rotation is a single vault.update_secret() call, with no redeploy, no environment variable change and no restart. The next agent call picks up the new key.

Two deployment models: BYOK and managed

When we build agent systems for clients, key ownership comes up in the first design conversation. Two architectures make sense, and the right one depends on what the client controls and what risk they want to carry.

BYOK: bring your own key. The client creates their own API keys at the provider (OpenAI, Anthropic, Google, whichever) and hands us only what the integration needs. We store those keys in Vault with the pattern above. The billing relationship stays between the client and the provider: they see their own usage dashboard, set their own spend limits and can revoke the key at the source without involving us. This is the right model when the client already has a provider relationship, cares about direct billing visibility, or has compliance requirements about who can sit in the credential chain.

Managed provisioning. We create and hold the provider account and keys on the client's behalf. It suits teams that do not want to manage API accounts at all: small teams, non-technical operators, or cases where the agent is a self-contained product we deliver rather than integrate. The keys are still encrypted at rest in Vault, scoped to the minimum access and revocable. The difference is that we hold the account, and we estimate the provider costs from the scope and include them in the monthly rate. If a client leaves, we generate new keys, hand them over and revoke the ones we held straight away.

Neither model stores keys in plaintext. That is a baseline requirement, and it should not need stating. The CRM we built inside Telegram runs on either model.

The audit trail question

Encryption at rest answers "what happens if the database leaks". It does not answer "which agent made which API call, and when". Those are separate properties, and both matter.

Every provider call our agents make goes through a thin middleware layer that logs the provider name, the model, the token counts and the user or tenant identifier, before the call is made and after it returns. The logs are append-only and shipped to a sink separate from the application database. If a key is compromised and rotated, you have a timestamped record of every call made with it, which helps you size the blast radius and supports any dispute with the provider.

That is also why scoping matters together with logging. A scoped key that is logged gives you containment and visibility. A root key with logging gives you visibility but a wide blast radius. A scoped key without logging gives you containment but no forensics. You want both.

What to check in your own stack

If you have an agent system running in production, these are the five questions worth asking this week:

  • Where are your provider API keys stored? Are they in .env, a TEXT column, or a proper encrypted store?
  • Could a database backup restore in staging expose production keys?
  • Are your keys scoped, or are they all org-level with full permissions?
  • How long would it take to rotate every key if you found one had been compromised at 2am?
  • Do your logs tell you which calls were made with which key, and is that log in a separate system that a compromised app database cannot overwrite?

If you cannot answer all five cleanly, you have gaps that haven't been triggered yet.

The point

"We don't store your keys in plaintext" is table stakes. The real question is whether the full stack is in place: encryption at rest with application-layer key wrapping, minimum-necessary scoping, clean revocation paths, EU-resident infrastructure where it matters, and an audit log that is independent of the application. That stack isn't complicated to build, but it takes a deliberate choice at each layer instead of the nearest .env file.

BYOK or managed, the architecture is the same. What changes is who holds the provider account, and you should make that choice on purpose.

Read next: Why your AI's memory stores your questions as facts (and how to stop it)

Questions about AI agent API keys

What does BYOK mean for AI agents?

BYOK means bring your own key: you create the API keys at the provider, such as OpenAI, Anthropic or Google, and hand over only what the integration needs. The billing stays between you and the provider, so you see your own usage dashboard, set your own spend limits and can revoke a key at the source without involving us.

Where should an AI agent store its API keys?

An AI agent should store its API keys encrypted at the application layer, never in a .env file or a plain TEXT column. Each key is encrypted with a data encryption key, which is wrapped by a key held in a secrets manager such as Fly.io secrets, Supabase Vault or a dedicated KMS. A full database backup then holds only ciphertext.

How do you rotate an API key without downtime?

To rotate an API key without downtime, keep key storage separate from agent configuration, so the agent holds a reference to the key record instead of the key itself. With Supabase Vault, rotation is a single vault.update_secret() call, with no redeploy, no environment variable change and no restart. The next agent call picks up the new key.

Where do your keys stand?

At a free audit we review your agent architecture against these five questions and give you a written findings report, with no sales pressure.