Sub topic 3
How keys leak
This chapter assumes you can use a terminal, make a Git commit and push, read short Python or JavaScript snippets, and know roughly what an HTTP API request is. You already know that an API key authorizes requests and bills the account that owns it. Here you will learn the routes by which keys escape, so the protections in later chapters make sense.
Leaks are usually ordinary mistakes
Few keys are stolen by clever attacks. Most leak because the key was copied into a place that more people, or more machines, can read than the developer intended. Three facts explain most incidents:
- Copies are cheap and hard to track. A key pasted into a file, chat message, or log line becomes a second copy that you must also find and remove.
- Many places are permanent or public. A pushed Git commit, a published package, and a public video all outlive your intention to delete them.
- Automated scanners find keys within minutes. Bots watch public code hosts and look for known key formats. Once a key is public, assume someone has already copied it.
A leaked LLM key is costly because the attacker's requests are billed to you. They can also use your quota, which causes outages for your own app.
Committing the key to version control
This is the most common route. A developer hard-codes a key to test quickly, then runs git add . and pushes.
# app.py - do NOT do this
api_key = "paste-your-key-here" # now part of every future commitDeleting the line in a later commit does not help. Git stores every earlier version, so the key stays in history. Anyone who clones the repository, or any fork made before you cleaned up, still has it.
You can check whether a string ever appeared in your history with Git's pickaxe search:
git log --all --oneline -S"paste-your-key-here"Each commit listed added or removed that exact string. Replace the example text with the first part of your real key to test whether it was ever committed.
A related mistake is committing the .env file. The file was meant to keep the key out of code, but if Git tracks it, it behaves like hard-coded source. Chapter 6 covers .gitignore.
Other file types are easy to forget:
- Jupyter notebooks store cell outputs, so a printed key is saved in the
.ipynbfile. - Config files such as
config.json,settings.yaml, ordocker-compose.ymloften get anAPI_KEYvalue added while testing. - Backup or editor files such as
.env.bakor.env.localare not matched by a rule that only names.env.
Shipping the key to the client
A browser or mobile app runs on the user's device. Anything sent to it can be read by the user, including a key.
- JavaScript bundles. A key in front-end code, or in a build-time variable that is inlined into the bundle, is plain text in the downloaded file. Minification does not hide it.
- Network requests. If the browser calls the LLM provider directly, the key appears in the request headers, and anyone can see it in the developer tools network tab.
- Mobile apps. An app package can be unpacked, and its strings searched. Traffic can be inspected with a proxy.
- Source maps. These map minified code back to the original and sometimes expose values that the bundle seemed to hide.
Many front-end tools make this easy to get wrong. Some frameworks only expose environment variables with a specific prefix to the browser. The prefix means "public". If you put a key behind such a prefix, you have published it. Chapter 9 covers the correct design, which is to call your own backend.
Writing the key into logs and error messages
Applications and libraries log a lot, and a key can end up in the output without anyone typing it.
The usual cause is putting the key in a URL query string. URLs are logged by web servers, proxies, browsers, and error handlers. This runs offline and shows how the key becomes part of the URL:
import requests
request = requests.Request(
"GET",
"https://api.example.com/v1/models",
params={"key": "fake-key-123"},
).prepare()
print(request.url)
# https://api.example.com/v1/models?key=fake-key-123Any exception that includes the URL, or any access log that records it, now contains the key. Sending the key in an Authorization header avoids this particular route, although headers can also be logged if you turn on verbose or debug logging.
Other common log leaks:
- Printing the whole config object or
os.environwhile debugging. - Debug logging of HTTP clients that dump request headers.
- Crash reporters that attach environment variables or local variables to each error report.
- Printing the full request while troubleshooting a failed call, then leaving the print in place.
Logs are often shipped to third-party services and kept for months, which adds more copies you cannot easily delete.
Sharing it by accident
The key often leaves through a human channel instead of through code.
- Screenshots and screen recordings. A terminal, a
.envfile open in an editor, or a provider console page can show the key. This happens in tutorials, bug reports, and conference talks. Some provider consoles show the key only once, so people tend to capture it right then. - Chat, email, and tickets. Pasting a key to a teammate or into a support ticket leaves it in searchable history, possibly visible to a whole channel.
- Questions to forums and AI assistants. Pasting a full code sample or error output to get help can include a real key. Treat anything you paste into a public or third-party service as published.
- Shared documents. Wikis, README files, and onboarding docs sometimes contain "working" example keys.
Build and deployment artifacts
Keys can be baked into things that are later copied or published.
- Container images. A
COPY . .step copies.envinto the image. Build arguments andENVlines in a Dockerfile are stored in the image layers and visible withdocker history. Anyone who can pull the image can read them. - CI logs. Build logs are often readable by many people, and public projects show them to everyone. A script that echoes its environment, or a tool run with verbose output, can print a secret. Most CI systems mask values they know are secrets, but masking can fail if the value is transformed, for example encoded or split.
- Published packages. Packaging tools may include files you did not mean to ship, such as a local
.env, when no ignore rules are set. - Cloned or copied environments. Sharing a whole home directory, VM snapshot, or dev container image shares every key stored in it.
Third parties and old copies
Some leaks come from systems you do not control.
- Dependencies and plugins. A malicious or compromised package that runs on your machine can read environment variables and send them elsewhere. Environment variables are not protected from code running in the same process.
- Former team members and contractors. A key they once held remains valid until you revoke it.
- Old keys that were never deleted. Unused keys in old projects, demo apps, and forgotten scripts keep working and widen the attack surface.
What the routes have in common
| Route | Who can read the copy | How long it lasts |
|---|---|---|
| Git history | Anyone with repo access, plus forks | Permanent unless history is rewritten, and forks keep it |
| Client bundle or app | Every user of the app | As long as the old version is cached or installed |
| Logs and crash reports | Operators and log vendors | Retention period, often months |
| Screenshots and chats | Viewers, channel members, archives | Indefinite |
| Container image or CI log | Anyone who can pull or view | Until images and logs are deleted |
In every row, you cannot reliably take the copy back. The effective fix is to make the key worthless by revoking it, which Chapter 13 covers. The earlier chapters on environment variables, .gitignore, and server-side calls reduce how many copies exist in the first place.
Exercise
A teammate says: "I removed the key from app.py in my next commit, so the repo is clean." Name two reasons that is not enough, and the action that actually fixes the problem.
Show answer
The key is still in the earlier commit, so anyone who clones the repository or already forked it can read it from history. It may also have been copied elsewhere, such as into CI logs or a chat message. The action that fixes it is to revoke the key in the provider console and issue a new one. Removing it from history is only a cleanup step.
Exercise
Your front-end framework exposes environment variables that start with PUBLIC to the browser. You store the key as PUBLICLLMAPIKEY so your page can call the provider directly. Is the key secret? Explain how someone would read it.
Show answer
No. The PUBLIC_ prefix means the value is inlined into the JavaScript sent to every visitor, so it is plain text in the bundle. Anyone can open the page source or the developer tools, and they can also see the key in the Authorization header of the network request. The call should go through your own backend instead.