11 min read

AI agent API key security: let agents use models without seeing the key

AI agent API key security: let agents use models without seeing the key
Read aloud by your browser. Nothing is downloaded.

Part of AI Tools & Automation — automating real work with local AI models.

✅ REAL DATA — LLM Vault 0.1.0 (Rust, open source) · 13 gateway security tests against a mock provider · live runs with Ollama (qwen3:0.6b) and llama.cpp (Qwen3.5-2B) · Windows 11 · AMD Radeon PRO W7900.

AI agent API key security has one weak spot: the agent usually holds the key it uses. In this guide I show how to let a coding agent call paid models while the provider key stays in an encrypted vault the agent cannot read. The tool is LLM Vault, the open-source desktop password manager with a built-in LLM gateway that I designed and released.

Key takeaways
  • An agent that can read .env or run shell commands can read any key you give it. Hiding the file does not change that.
  • The fix is a model change: the agent gets an invoke_model() operation, never a get_secret() operation.
  • LLM Vault keeps keys in a KeePass KDBX 4 file and exposes only /v1/chat/completions, /v1/messages, /v1/embeddings and /v1/models.
  • In my tests, 24 endpoint probes returned zero secrets, and a provider error that echoed the key reached the client as [REDACTED].
  • The gateway added about 7 ms to a 1.1 s local model call.

Why AI agent API key security breaks with .env files

Coding agents are no longer chat windows. They read the repository, run terminal commands and execute Python. As a result, every secret the developer can read, the agent can read too.

Here is the everyday scenario. First, a developer starts an agent in VS Code. Next, the Azure AI Foundry key sits in .env, in an environment variable or in the OS credential store. Then the agent processes untrusted text: a README, a tool result or a dependency. A hidden instruction in that text asks the agent to print the key, and the key ends up in a log, a model response or a remote server.

The consequences are expensive. Someone else burns your token budget. Moreover, you must rotate the key in every script that uses it. Notably, this happens even when the key never touched Git.

OWASP lists this pattern as LLM01 Prompt Injection. The core gap is simple. “The application may use the API” should not mean “the application may read the API key”. In practice, every common storage method merges those two rights.

Which API key storage methods leak to AI agents

Each tool below protects the key at rest. None of them controls what happens after the key is handed out.

MethodWhat it gives youWhat it does not solve
.env and environment variablesEasy key delivery to scriptsAny process with file or process access reads it
Windows Credential ManagerA system store instead of the repoCode running as your user can request it
KeePass / KeePassXCAn encrypted database with a master passwordNo control once the secret is copied out
Cloud Key VaultCentral secrets, RBAC and auditAn over-privileged agent still fetches the secret
A plain LLM proxyHides the key behind an endpointWithout auth and limits, anyone on the box uses it

The API key security fix: invoke_model() instead of get_secret()

The secure design inverts the flow. Instead of handing the key to the client, the vault performs the call itself. The client receives a narrow permission, not a credential.

LLM Vault implements that inversion in five steps:

  1. First, the agent sends POST /v1/chat/completions with model: foundry-glm and a client token.
  2. Next, the vault identifies the client, the model, the limits and the rules.
  3. Then a policy or the user approves the call: once, for the session, or with a standing rule.
  4. After approval, LLM Vault calls the provider. Its key exists only inside the vault process and the outbound TLS request.
  5. Finally, the agent receives the answer. Tokens, cost and the decision go to the audit log.

The client token is a permission to call the gateway. It is not a provider key. Furthermore, it has a model allow-list, an expiry date, a budget and a rate limit, and you revoke it with one click.

What the AI agent sees instead of the API key

From the agent’s side, nothing exotic happens. It talks to a standard OpenAI-compatible endpoint. Only the base URL and the credential change:

import os
from openai import OpenAI

# The token can call approved models; it cannot read any key.
client = OpenAI(base_url="http://127.0.0.1:8765/v1",
                api_key=os.environ["VAULT_CLIENT_TOKEN"])

reply = client.chat.completions.create(
    model="foundry-glm",
    messages=[{"role": "user", "content": "Review code"}])
print(reply.choices[0].message.content)

Consequently, existing agents keep their workflow. The same applies to Claude Code through /v1/messages and to GitHub Copilot Chat, which I cover in the VS Code Copilot custom endpoint guide.

Free ebook

Free AI Video, Generated Locally

Working scripts and measured benchmarks. Free.

No spam. Unsubscribe at any time.

How LLM Vault enforces API key security

The design rests on one rule: no network endpoint returns a key, a password or the configuration. Everything else supports that rule.

The gateway exposes four operations, nothing else

The whole network surface fits in a few lines. There is no admin API on the port, so a local agent cannot reach settings either:

// The only routes a client can reach. No route reads a secret.
Router::new()
    .route("/health", get(health))
    .route("/v1/models", get(models))
    .route("/v1/chat/completions", post(chat_completions))
    .route("/v1/messages", post(messages))
    .route("/v1/embeddings", post(embeddings))
    .fallback(not_found)

The desktop window talks to the core in-process. Therefore, configuration changes never travel over HTTP.

Configuration lives inside the encrypted file

A subtle attack targets configuration, not the key. If an agent could edit a settings file, it could point the “Azure” provider at its own server and receive the key in the next request. LLM Vault stores provider URLs, clients and rules inside the KDBX file. That file is encrypted and integrity-protected with HMAC, so a tampered file simply fails to open. In addition, the HTTP client never follows redirects, and remote providers must use HTTPS.

Consent, budgets and limits

Each client token carries its own policy. You choose between asking on every request, asking once per session or pre-approving the client. On top of that, daily and monthly budgets stop runaway loops with HTTP 429.

LLM Vault consent prompt asking whether API Analyst may use Azure AI Foundry gpt-5-mini
The consent prompt names the client, agent, project and model. The buttons arm after a short delay, so a script cannot click them instantly.

What I tested, and the numbers

Every security property of LLM Vault has an automated acceptance test. The suite runs against a mock provider that checks the real key on every request.

CheckResult
24 probes (GET and POST on 12 paths such as /v1/secrets, /v1/config, /admin)0 responses contained a key or password
Missing token, wrong token, revoked tokenHTTP 401
Model outside the allow-list, consent denied, consent timeoutHTTP 403
Vault locked during trafficHTTP 423 vault_locked
Budget 0.001 USD, second callHTTP 429 budget_exceeded
Request from a web page (Origin header)HTTP 403
Gateway overhead, Ollama qwen3:0.6babout 7 ms on a 1,087 ms call

How the redactor stops a key echoed in an error

Some providers echo part of the key in error messages. To simulate that, the mock provider answers with bad request for key sk-test-UPSTREAM-SECRET-…. The client received this instead:

{"error": {"type": "upstream_error",
  "message": "Upstream provider returned HTTP 400: bad request for key [REDACTED]"}}

The redactor removes every configured key, plus its first 10 and last 6 characters, because providers like to print those. It also masks common key shapes such as sk-…, AIza… and Bearer …. Finally, the test reads the raw SQLite audit file and confirms the key is not there either.

LLM Vault dashboard with calls, tokens, cost by provider and daily trend on synthetic demo data
The dashboard shows calls, tokens, cost per provider and per agent. These numbers come from the built-in demo mode with synthetic data.

Limits: when a desktop vault is not enough

Honesty matters here. If an agent runs arbitrary code as the same OS user that unlocked the vault, a consent dialog cannot guarantee secrecy. Such an agent could, for example, read process memory or automate the UI.

For that threat, LLM Vault ships llmvault-server, a headless gateway. You run it on a separate VM, under a separate OS account or on another device. The agent then reaches only the HTTP endpoint. In headless mode, only pre-approved clients and standing rules work, because nobody sits there to click “Allow”.

Watch out — a stolen client token still works until you revoke it. Keep tokens scoped to the models a client needs, give them an expiry and set a daily budget.

Set up the vault in five minutes

The setup takes five short steps, and none of them touches your agent’s code. First, install LLM Vault and create a profile with a user name and a login password. Next, create a vault. That is a KDBX 4 file protected by a separate master password, and you can also open an existing KeePass database instead.

Then open the Providers page and pick an integration from the catalog. For example, “Ollama (local)” needs no key, while “Azure AI Foundry” or “Ollama Cloud” asks for one. The key goes straight into the vault’s “LLM Providers” group. After that, the discovery dialog lists the provider’s models, and you select the ones to expose as aliases.

Finally, create a client token on the “Clients & agents” page. Give it a name such as “VS Code – Code Reviewer”, restrict it to two models and set an expiry of 30 days. The token appears exactly once, together with ready snippets for Python, Claude Code, curl and VS Code. As a result, the agent only ever sees lvk_…, never the provider key.

# Quick check from any terminal: list the models this token may use
curl http://127.0.0.1:8765/v1/models -H "Authorization: Bearer lvk_..."

Where agent API key security pays off

  • A team shares one Azure AI Foundry deployment, and each developer gets a revocable token instead of the key.
  • Custom agents in .github/agents review code on a paid model without any key in the workspace.
  • Nightly Python batch jobs run against local Ollama models with a cost estimate per project.
  • A consultant demonstrates agents to a client, and the vault logs every call for the invoice.

For the local-model side, see the local LLM gateway measurements. The storage design is explained in the KeePass-compatible vault deep dive.

LLM Vault activity log listing requests with model, client, agent, consent type, tokens and cost
Every request keeps its policy decision, consent type and usage source, so cost reports stay explainable.

Frequently asked questions

Can a prompt injection make the gateway reveal the key?

No. The gateway has no operation that returns a key, so there is nothing to trigger. An injected prompt can still spend tokens, which is why consent, budgets and rate limits exist.

Is a client token just another API key for the agent?

It is a credential, but a much weaker one. It works only against your local gateway, only for listed models, only until it expires, and you can revoke it instantly.

Do I have to change my agent’s code?

Usually not. You change the base URL to http://127.0.0.1:8765/v1 and use the client token as the API key. OpenAI SDKs, the Anthropic SDK and Claude Code work as they are.

Which providers does it support?

The catalog has 38 integrations. They include Ollama local and ollama.com, LM Studio, llama.cpp, vLLM, OpenAI, Azure AI Foundry, Anthropic, Gemini, OpenRouter, Groq, Mistral and DeepSeek.

What happens when I lock the vault?

Every gateway call returns HTTP 423 immediately. Decrypted data is dropped from memory, and session approvals are cleared.

Is LLM Vault open source?

Yes. It is licensed under Apache-2.0 and built in Rust with the Slint UI toolkit, so it ships as a single native executable.

Summary

AI agent API key security fails whenever the agent can read the key it uses. The robust fix replaces get_secret() with invoke_model(). LLM Vault keeps keys in a KeePass-compatible KDBX 4 file and exposes only model calls. In addition, it adds consent, budgets and an audit trail. In my tests, 24 probes returned no secrets and an echoed key arrived as [REDACTED]. Meanwhile, the gateway cost about 7 ms per call. For hard isolation from terminal-capable agents, run the headless gateway outside the agent’s account.

LLM Vault itself is free and open source. The installer, the portable version and the example scripts from the videos are on the LLM Vault download page.

The download bundle ai-agent-api-key-security.zip contains the security test suite, the Python and curl examples and the gateway route code shown above.

Companion code — the fragments above are the working parts: the route table that defines the entire network surface, the client snippet that replaces a provider key with a vault token, and the redaction rule behind the leak test.

Free ebook

Free AI Video, Generated Locally

Run Wan 2.1 in ComfyUI on your own GPU — the scripts I use, measured times, sample clips. No cloud, no API keys.

No spam. Unsubscribe at any time.

Did this article help?
Artur Poniedziałek
Artur Poniedziałek
IT Expert & Project Manager
🤖 AI ⚡ PM 🐍 Python 🖥️ Local AI

IT Expert & Project Manager with 15+ years of experience. Exploring practical AI applications — from local LLMs and RAG systems to workflow automation. Writing to share knowledge and inspire others to experiment with new technologies.

2 responses to “AI agent API key security: let agents use models without seeing the key”

Leave a Reply

Your email address will not be published. Required fields are marked *