LLM 0.37.2, released November 11, 2026, fixes two bugs that could send your OpenAI API key to a third-party provider's server when that provider's own key was missing. If you use LLM, upgrade and compare every api_key_name with llm keys list. If your iOS app's backend uses the OpenAI SDK to call other providers through a custom base URL, check that every client passes its own key, that nothing falls back to OPENAI_API_KEY, and add a canary test that fails if the OpenAI key ever reaches another host.
On November 11, 2026, Simon Willison shipped LLM 0.37.2, a security release for his popular command-line tool for large language models. It fixes two bugs that could send your OpenAI API key to a different company's server. The release notes credit Daniel de Araujo for the report, and two GitHub advisories, both rated Moderate, explain how it happened.
If you use LLM, the fix is one upgrade. The more useful lesson for anyone shipping an iOS app with AI features is the pattern behind the bug. A tool that talks to "OpenAI-compatible" providers quietly fell back to the OpenAI key when the provider's own key was missing. The official OpenAI SDKs for Python and Node do the same thing by design when you build a client with a custom base URL and no key. Plenty of AI-built app backends are written exactly that way.
Below are the two LLM bugs, the steps for LLM users, and a small scanner plus a canary test for checking your own app's backend. Both scripts were run locally while writing this post.
What happened in LLM 0.37.2
LLM can talk to any provider that copies the OpenAI API format. You list those providers in a file called extra-openai-models.yaml, giving each one an api_base (the provider's URL) and, optionally, an api_key_name (the name of a key you stored with llm keys set). Version 0.37 added an llm openai endpoint add command that manages that file for you.
The advisories describe two separate ways the OpenAI key could end up at that third-party URL.
Bug 1: a missing named key fell back to OPENAI_API_KEY
Advisory GHSA-v9h7-jj4g-f862 covers versions 0.6 through 0.37.1. If a custom model set both api_base and api_key_name, but no key had ever been stored under that name, LLM did not stop with an error. It looked for the named key, found nothing, and then used the OPENAI_API_KEY environment variable instead. That value went to the third-party host as a Bearer token.
The advisory lists the ordinary ways to hit this: a typo in api_key_name, forgetting to run llm keys set, or using a machine where only OPENAI_API_KEY is exported. Nothing in the tool told you which key had been sent. The fix in 0.37.2 makes LLM report a missing key instead.
Running the advisory's setup against a local capture server shows the difference clearly. With 0.37.1, the local server received Bearer sk-CANARY-llm0371, the fake value placed in OPENAI_API_KEY. With 0.37.2, the same command stopped with Error: No key found - add one using 'llm keys set thirdparty' and the server received nothing.
Bug 2: the chat_completions delegate kept the OpenAI key
Advisory GHSA-r639-rr7r-x72w affects versions from 0.32a2 up to 0.37.1 and is credited to BluePlexus. It applies to a custom model with api_base and responses: true but no api_key_name. When you ran that model with -o chat_completions 1, LLM built an internal helper object to make a Chat Completions call. That helper did not inherit the outer model's key setting, so it fell back to its class default, which is the OpenAI key. The key could come from OPENAI_API_KEY or from llm keys set openai.
The advisory notes that LLM's own documentation says the opposite should happen: when api_base is set, the configured OpenAI key is not sent by default. The suggested fix was a single line copying the key setting onto the helper. Both bugs are classed as CWE-201, Insertion of Sensitive Information Into Sent Data.
If you use LLM, do this now
- Check your version with
llm --version. Anything below 0.37.2 is affected by at least the first bug, as long as you have custom OpenAI-compatible models configured. - Upgrade. With pip that is
pip install -U llm. With pipx,pipx upgrade llm. With Homebrew,brew upgrade llm. - Open your endpoints file.
llm openai endpoint pathprints whereextra-openai-models.yamllives, andllm openai endpoint listshows the saved endpoints. - Compare every
api_key_namein that file withllm keys list. Any name in the YAML that is missing from the list is a model that would have used your OpenAI key on older versions. - Look for models with
responses: trueand noapi_key_name, and think about whether you ever ran them with-o chat_completions 1. - If either check matches, assume the third-party provider received your OpenAI key. Revoke that key in your OpenAI dashboard, create a new one, and update every place that uses it.
The second bug needed a specific option, so many people will not be affected. The first one needed nothing unusual at all. A forgotten llm keys set on a laptop that exports OPENAI_API_KEY in its shell profile was enough.
Why this matters for your iOS app
Many apps built with Cursor, Claude Code, Bolt, Lovable or Rork call more than one AI provider. A common setup is a small backend, often a serverless function, that uses the OpenAI SDK and points it at OpenRouter, Groq, Together or a self-hosted gateway by changing the base URL. The SDK is convenient because all those services accept the same request shape.
The official OpenAI SDKs read OPENAI_API_KEY from the environment whenever you do not pass a key. They do this regardless of which base URL you set. The SDK has no idea that the base URL now belongs to another company.
That behaviour was checked locally with the current packages, openai 3.49.0 for Python and openai 7.55.0 for Node, against a tiny server on 127.0.0.1 that only records the Authorization header. Each test set OPENAI_API_KEY to a fake canary value:
- Python,
OpenAI(base_url="http://127.0.0.1:8799/v1")with no key: the server receivedBearer sk-CANARY-env. - Python,
OpenAI()withOPENAI_BASE_URLset in the environment to the local server: the server received the canary key. - Node,
new OpenAI({ baseURL: "http://127.0.0.1:8799/v1" })with no key: the server receivedBearer sk-CANARY-node.
The SDKs are working as documented here. Reading the key from the environment makes sense for code that talks to OpenAI, and it turns into a leak when your code talks to someone else and you assumed the key would come from somewhere more specific. The LLM bug is the same mistake inside a well-maintained open-source tool, which is a good sign of how easy it is to make.
The four shapes this takes in real backends
The first is a client with a custom base URL and no explicit key. Someone wires up Groq or Together, sets base_url, and expects the key to come from a provider-specific variable. It never does. If the provider's key is missing, requests fail with a 401 from the provider. If OPENAI_API_KEY also exists in that environment, the provider gets it.
The second is a fallback chain written on purpose. Lines like os.environ.get("OPENROUTER_API_KEY") or os.environ["OPENAI_API_KEY"] look tidy. They are written so the app "just works" in development. In production they mean any missing or misnamed variable sends your OpenAI key to the router.
The third is a shared env file. An .env file that contains a real OPENAI_API_KEY next to an OPENAI_BASE_URL pointing at a gateway sends that key to the gateway on every call. Sometimes that is intended, for example with a proxy you run yourself. Often it is left over from trying a service once.
The fourth is a key inside the app itself. AI tools still sometimes generate Swift code that calls a provider directly with a key stored in the app bundle, an .xcconfig file or the Info.plist. Anything shipped inside an IPA can be pulled out by whoever downloads it. If your app does this, the fallback problem is the smaller issue: move the calls behind a backend you control before anything else. Backdoored Claude Code Extension in Cursor: Check Your Mac, Then Rotate These iOS Keys shows how quickly a key that leaves your control gets used.
Scan your backend for the fallback
The script below walks a folder and flags the first three shapes. It looks at Python, JavaScript, TypeScript, Swift, Go and Ruby files, plus any file whose name starts with .env. It needs only Python 3 and has no dependencies.
#!/usr/bin/env python3
"""Flag places where an OpenAI key could be sent to a non-OpenAI endpoint.
Usage: python3 key_fallback_scan.py path/to/backend
"""
import re, sys, pathlib
CODE = {".py", ".js", ".mjs", ".cjs", ".ts", ".swift", ".go", ".rb"}
ENVF = (".env", ".env.local", ".env.production", ".env.example")
client_call = re.compile(r"\b(?:Async)?OpenAI\s*\(")
base_kw = re.compile(r"base_?url\s*[=:]", re.I)
key_kw = re.compile(r"api_?key\s*[=:]", re.I)
fallback = re.compile(
r"(?:\bor\b|\|\||\?\?)\s*(?:os\.environ(?:\.get)?\s*[\[(]\s*|process\.env\.|"
r"ProcessInfo\.processInfo\.environment\[\s*)[\"']?OPENAI_API_KEY")
def scan_code(p, text, hits):
lines = text.splitlines()
for i, line in enumerate(lines):
if fallback.search(line):
hits.append((p, i + 1, "falls back to OPENAI_API_KEY", line.strip()))
if client_call.search(line):
# look at the call plus the next 8 lines for its arguments
window = "\n".join(lines[i:i + 9])
depth, end = 0, len(window)
for j, ch in enumerate(window):
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
end = j
break
args = window[:end]
if base_kw.search(args) and not key_kw.search(args):
hits.append((p, i + 1, "custom base URL, no explicit key", line.strip()))
def scan_env(p, text, hits):
keys = dict(re.findall(r"^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)$", text, re.M))
if "OPENAI_BASE_URL" in keys and "OPENAI_API_KEY" in keys:
url = keys["OPENAI_BASE_URL"].strip("'\" ")
if "api.openai.com" not in url:
hits.append((p, 0, "OPENAI_API_KEY and a non-OpenAI OPENAI_BASE_URL in one env file", url))
def main(root):
hits = []
for p in pathlib.Path(root).rglob("*"):
if not p.is_file() or "node_modules" in p.parts or ".git" in p.parts:
continue
try:
text = p.read_text(errors="ignore")
except OSError:
continue
if p.name in ENVF or p.name.startswith(".env"):
scan_env(p, text, hits)
elif p.suffix in CODE:
scan_code(p, text, hits)
for p, n, why, snippet in hits:
print(f"{p}:{n}: {why}\n {snippet}")
print(f"\n{len(hits)} finding(s)")
return 1 if hits else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
Save it as key_fallback_scan.py and run python3 key_fallback_scan.py ./backend. It exits with code 1 when it finds something, so you can drop it into a CI step. Against a sample folder with a Groq client missing its key, a Python or fallback, a TypeScript ?? fallback, a Together client with no key and an .env file pointing at a gateway, it reported all five and left alone the one correct client that passes api_key=os.environ["OPENROUTER_API_KEY"].
It is a pattern match, so it has limits. It will miss a key loaded through a config library, a wrapper function that builds the client somewhere else, or a variable renamed through several steps. It can also flag a client that is fine because the key is injected some other way. Treat each finding as a line to read. A clean run only means nothing obvious turned up.
What the scanner caught on a Mac, and what it let through
The scanner was run with Python 3.12 on macOS 26.0.1 against a sample backend written for this post. It held a Python file with five OpenAI clients, a TypeScript file with two, an .env file pointing at a gateway, an .env.example that points at OpenAI itself, and a planted file under node_modules. It printed:
backend/.env:0: OPENAI_API_KEY and a non-OpenAI OPENAI_BASE_URL in one env file
https://gateway.example.com/v1
backend/api/providers.py:4: custom base URL, no explicit key
groq = OpenAI(base_url="https://api.groq.com/openai/v1")
backend/api/providers.py:5: falls back to OPENAI_API_KEY
router_key = os.environ.get("OPENROUTER_API_KEY") or os.environ["OPENAI_API_KEY"]
backend/api/route.ts:2: falls back to OPENAI_API_KEY
const key = process.env.GROQ_API_KEY ?? process.env.OPENAI_API_KEY;
4 finding(s)
The gateway .env, the Groq client with no key and both explicit fallbacks were found. The .env.example that uses OpenAI's own URL and the file under node_modules were skipped, as intended. Three cases got through, and they are worth knowing because each looks correct in a code review:
OpenAI(api_key=os.environ.get("TOGETHER_API_KEY"), base_url=...). The key is passed, so the scanner is satisfied. IfTOGETHER_API_KEYis missing,.get()returnsNone, which is the same situation as the LLM bug: a named key that does not exist.- The same thing with
os.getenv(...), spread over several lines. - In TypeScript,
new OpenAI(cfg)with the options in a variable defined elsewhere, andapiKey: process.env.DEEPSEEK_API_KEY, which isundefinedwhen the variable is missing.
Whether the SDK then reads OPENAI_API_KEY for a None or undefined key depends on how its constructor treats a missing value, and the canary test below is how to settle that for the version you run. The fix does not depend on the answer. Use the require pattern from the factory section, which fails when the variable is missing, and never .get(), getenv or a bare process.env for a key.
Prove it with a canary test
A scan finds suspicious lines. A test proves what actually goes over the wire. The idea is simple: put a fake value in OPENAI_API_KEY, point each non-OpenAI provider at a local server that records the Authorization header, make one call, and fail the test if the fake OpenAI value shows up.
For this to work, each provider's base URL has to be configurable through its own variable, which is good practice anyway. Here is a version using Python's built-in unittest:
# Run: python3 -m unittest test_key_crossing.py
import os, threading, http.server, json, unittest
from openai import OpenAI
CANARY = "sk-canary-must-never-leave-openai"
seen = []
class Capture(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", 0)))
seen.append(self.headers.get("Authorization", ""))
body = json.dumps({"id": "x", "object": "chat.completion", "created": 0, "model": "m",
"choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "ok"}}]}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
# Your provider factory. It reads its own key and its own base URL.
def make_router_client():
return OpenAI(base_url=os.environ.get("ROUTER_BASE_URL", "https://openrouter.ai/api/v1"),
api_key=os.environ["ROUTER_API_KEY"])
def make_router_client_buggy():
return OpenAI(base_url=os.environ.get("ROUTER_BASE_URL", "https://openrouter.ai/api/v1"))
class KeyCrossing(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.srv = http.server.HTTPServer(("127.0.0.1", 0), Capture)
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
os.environ["OPENAI_API_KEY"] = CANARY
os.environ["ROUTER_BASE_URL"] = f"http://127.0.0.1:{cls.srv.server_port}/v1"
os.environ["ROUTER_API_KEY"] = "sk-router-test"
def setUp(self):
seen.clear()
def call(self, factory):
factory().chat.completions.create(model="m", messages=[{"role": "user", "content": "hi"}])
def test_router_never_gets_openai_key(self):
self.call(make_router_client)
self.assertEqual(seen, ["Bearer sk-router-test"])
def test_buggy_factory_is_caught(self):
self.call(make_router_client_buggy)
self.assertIn(CANARY, seen[0]) # shows the test would catch the leak
if __name__ == "__main__":
unittest.main()
Both tests pass with openai 3.49.0. The second one exists only to show that the check works: the buggy factory really does send the canary. In your own project, replace the two factories with the real functions your backend uses for each provider, keep one test per provider, and delete the "buggy" example. The server binds to port 0, so the operating system picks a free port and the test never touches the internet.
The same approach works in a Node backend. Start an http server on a random port, set OPENAI_API_KEY to a canary in the test setup, point the provider's base URL variable at the server, and assert on the recorded header.
The fix: one factory per provider, failing closed
The safe pattern is boring on purpose. Every provider gets its own small function, which reads its own key by name, raises an error if the key is missing, and never touches OPENAI_API_KEY.
import os
from openai import OpenAI
def require(name: str) -> str:
value = os.environ.get(name)
if not value:
raise RuntimeError(f"{name} is not set")
return value
def openai_client() -> OpenAI:
return OpenAI(api_key=require("OPENAI_API_KEY"))
def groq_client() -> OpenAI:
return OpenAI(base_url="https://api.groq.com/openai/v1",
api_key=require("GROQ_API_KEY"))
def openrouter_client() -> OpenAI:
return OpenAI(base_url=os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1"),
api_key=require("OPENROUTER_API_KEY"))
In TypeScript the shape is the same:
import OpenAI from "openai";
function requireEnv(name: string): string {
const v = process.env[name];
if (!v) throw new Error(`${name} is not set`);
return v;
}
export const groq = () =>
new OpenAI({ baseURL: "https://api.groq.com/openai/v1", apiKey: requireEnv("GROQ_API_KEY") });
A few habits make this stick:
- Leave
OPENAI_API_KEYout of environments that do not need it. If a function only calls OpenRouter, its environment should not contain an OpenAI key at all. Serverless platforms let you set variables per function or per service. With no OpenAI key present, a fallback has nothing to leak. - Avoid
OPENAI_BASE_URLin shared environments. It changes the destination for every client that does not set a base URL explicitly, including code paths you forgot about. - Use separate keys per environment and per service: one for local development, one for staging, one for production. If one leaks, you revoke one and the others keep running.
- Put a spending limit on each key or project if your provider offers one, so a leaked key costs a known amount at most.
- Add the scanner and the canary test to CI. The scanner is cheap and catches new code. The test catches refactors that move client creation somewhere the scanner cannot see.
Test the missing-key case too
The canary test above sets ROUTER_API_KEY, so it proves the router client sends its own key when the key is there. The bug in LLM happened when the named key was not there. Add one more test per provider that removes the provider's key, keeps the canary in OPENAI_API_KEY, and expects the factory to fail before any request is made:
def test_router_fails_without_its_key(self):
saved = os.environ.pop("ROUTER_API_KEY")
try:
with self.assertRaises((KeyError, RuntimeError)):
self.call(make_router_client)
self.assertEqual(seen, []) # nothing reached the server
finally:
os.environ["ROUTER_API_KEY"] = saved
With the factory from the test file, which reads os.environ["ROUTER_API_KEY"], the lookup raises KeyError and the server sees nothing. With a factory that uses os.environ.get, this is the test that tells you what your SDK version does when it is handed None. This test was written for this post and has not been run, because the OpenAI package is not installed on the Mac used here. Run it in your own project, where the package already is.
When you prompt an AI tool to add a provider
Coding agents write the fallback pattern because it looks helpful. When you ask Cursor or Claude Code to add a new AI provider to your backend, say what you want in plain words. Something like: "Create a separate client function for this provider. Read its key from its own environment variable, raise an error if it is missing, and do not fall back to OPENAI_API_KEY or OPENAI_BASE_URL. Add a unit test that sets OPENAI_API_KEY to a fake value and checks it is never sent to this provider."
Then read the diff. Search it for OPENAI_API_KEY, or os.environ, ?? and || near anything that looks like a key. If your project has a CLAUDE.md or AGENTS.md file, add the rule there so it applies to every future change, not only this one.
If a key may already have leaked
If the scan or the test finds a real fallback that has been running in production, assume the other provider has seen your OpenAI key. Even a trustworthy provider keeps logs, and a breach on its side would now include your key. Claude Code's "Don't Ask Again" Can Save Your Passwords covers another quiet way keys end up where they should not be.
- Create a new OpenAI key and deploy it everywhere the old one was used.
- Revoke the old key in the OpenAI dashboard once the new one is live.
- Check usage for the old key over the period the fallback existed. Look for models, volumes or times that do not match your app.
- Fix the code with the factory pattern above and add the canary test so the fallback cannot come back.
- Do the same for any other key that sat in the same environment, since the same mistake can apply to other providers.
For the LLM command-line tool specifically, the same steps apply to the OpenAI key stored on your machine or exported in your shell.
A short checklist
- LLM users: upgrade to 0.37.2 and compare every
api_key_namewithllm keys list. - Run
key_fallback_scan.pyon your backend and read every finding. - Add one canary test per non-OpenAI provider.
- Remove
OPENAI_API_KEYandOPENAI_BASE_URLfrom environments that do not need them. - Make sure no provider key is stored inside the iOS app bundle.
- Rotate any key that may have been sent to the wrong host.
FAQ
Which versions of LLM are affected?
The missing-key fallback affects versions 0.6 through 0.37.1. The -o chat_completions 1 issue affects versions from 0.32a2 through 0.37.1. Version 0.37.2 fixes both.
Is this a bug in the OpenAI SDK?
No. The SDKs document that they read OPENAI_API_KEY from the environment when no key is passed. The risk comes from using the OpenAI SDK to talk to other providers without passing their key explicitly.
Does this affect Swift code in my app?
The tests in this post covered the Python and Node SDKs only. Apps usually do not read server-style environment variables at runtime, so the bigger Swift question is whether a provider key is shipped in the app at all. If it is, move those calls to a backend.
Will the scanner find every case?
No. It catches common patterns in plain code and env files. Use the canary test for proof.
Do I have to rotate my OpenAI key?
Is reading the key with os.environ.get safe?
Not if the variable can be missing. It passes None in that case, which is the same missing-key situation that caused the LLM bug. Read the key with a function that raises an error when it is not set, and add a test that removes the key and checks that no request is sent.
Only if a fallback could actually have fired. If every non-OpenAI client always had its own key set, and you never ran LLM with a missing named key, the OpenAI key did not travel. If you cannot tell, rotating costs a few minutes.
Keep the rules in your repo
If you use Claude Code on an iOS project, Claude Code + Xcode: The Production iOS Workflow Kit is a set of copy-ready CLAUDE.md and AGENTS.md templates, eight rules (one of them on privacy and security), six commands and ten iOS agents, with human approval gates around areas like auth, PII and signing. It is aimed at the iOS app side. It does not scan backends for API keys, and it cannot guarantee security or App Store approval, so the scanner and test above are still the way to check this specific problem.
Keep reading on JR Devhub
- AI Coding Costs: Why Your Agent Bill Is Mostly Re-Reading (and 7 Ways to Cut It)
- Claude Fable 5.2 Is Out. What to Change in Claude Code and Your App's API Calls Before You Switch
- Revolut Says Self-Hosting Cut Its AI Coding Bill 90%. Run This Math Before You Copy It
- OpenAI's $1.2M Run Produced 948 Linux Root Exploits. What to Change on Your Servers and CI
Sources
- Simon Willison: LLM 0.37.2 release notes (Nov 11, 2026)
- GHSA-v9h7-jj4g-f862: api_key_name falls back to OPENAI_API_KEY and sends it to a custom api_base
- GHSA-r639-rr7r-x72w: OpenAI API key sent to custom api_base by the -o chat_completions 1 delegate
- llm on PyPI
- openai Python SDK on PyPI
- openai Node SDK on npm
- Dev News Digest, 12 Nov 2026 06:00 (DEV Community)

Comments