[KongchangAI]
· 4 min read· 2,090 words

A Practical Security Checklist for OpenAI/Claude/Gemini API Keys

A Practical Security Checklist for OpenAI/Claude/Gemini API Keys

LLM API keys are billable bearer credentials—split them, expire them, cap them, and keep them server-side.

Using the OpenCode Console API key leak as a starting point, the article explains how LLM API keys differ from traditional passwords: they are billing credentials that work the moment they're held, with no second factor or login entry point as a buffer, so losses grow open-endedly. Drawing on official documentation from OpenAI, Anthropic, and Google, it lays out a complete line of defense: split keys by tool, project, and environment to shrink the blast radius; use creation-time expiration and organization policies to enforce rotation, and rehearse in advance to map out every place a key lives; replace after-the-fact alerts with hard spending limits; ensure keys exist only on the server via server-only, backend auth and rate limiting, and IP allowlists; and be cautious about pasting keys into third-party hosted tools, since deleting in the tool doesn't equal revocation. It closes with the order of operations for the first hour after a leak.

A security incident at OpenCode Console exposed the API keys of third-party model providers for 1.4% of users. Anthropic and Google revoked and banned the affected keys within hours, and OpenCode has yet to explain the attack path. The most valuable takeaway from this episode isn't "who got hit" but a repeatedly validated common-sense lesson: An LLM API key is a bearer credential—whoever obtains that string of characters can spend your money until the provider revokes it.

Based on reporting from The Hacker News and the official documentation of OpenAI, Anthropic, and Google (as of October 2026), the checklist below covers the full chain from key creation, storage, and spending limits to what to do in the first hour after a leak.

Why the cost of a leaked API key is open-ended

When a traditional password leaks, an attacker usually still needs to find a login entry point. When an API key leaks, the attacker directly gains billing capability. There's no second factor, no IP binding (unless you configure it yourself), and no "unusual login" alert.

What's worse, many teams use the same key across scripts, agents, SaaS tools, and production. Once it leaks, revoking that key means taking production down—so teams tend to "wait and see," and every minute of waiting generates a bill.

Splitting keys by tool, project, and environment is the first step to reducing the blast radius of a single point of failure. Revoking one key affects only one consumer, and the usage page can tell you directly which consumer was abused.

How the three providers organize keys differently

  • OpenAI: Keys belong to a project. The official key security article explicitly states that sharing keys violates the terms of service, and you can assign permissions to individual keys.
  • Anthropic: Workspaces are used to isolate environments and spending. New keys come in two flavors—personal keys (which act as you) and service account keys—both of which can be scoped to a single Workspace. Personal keys are automatically invalidated when the owner leaves the organization—exactly the behavior you want. The old Workspace keys are now marked as legacy.
  • Google: Each Gemini key belongs to a Google Cloud project, and usage from all keys under that project counts toward the project's spending cap. If you want each tool to have its own independent cap, you need to create separate projects.

BYOK (Bring Your Own Key) is a pattern that comes up repeatedly in this article but isn't expanded on in depth: users enter their own API key from the model provider into a third-party tool, and that tool makes model calls on their behalf. Its appeal is that users can directly leverage their existing billing and quotas without paying separately for the tool; but the cost is that ownership and usage of the key become separated—the key belongs to the user, while the calls are executed by the tool's servers. As a result, every BYOK tool faces the same set of design questions: is the key encrypted when stored, which roles are granted decryption capability, and can dashboard users read back the plaintext? Understanding this explains why "deleting a key in the tool" and "revoking a key on the provider side" are two entirely different things.

Make keys expire, and rehearse a rotation

A key that never expires remains valid forever as long as even one copy exists.

OpenAI project keys can be given an expiration date at creation time, and admins can also enforce a maximum key lifetime at the organization or project level. Anthropic requires you to choose a validity period at creation: 3 hours, 1 day, 7 days, 30 days, custom, or never; this cannot be changed after creation, organization policies can disable the "never expire" option, and keys valid for 14 days or more trigger an email reminder to the creator 7 days before expiration.

Google's Gemini key documentation doesn't mention an expiration mechanism; instead it tightens things in another way: as of May 28, 2026, new AI Studio keys are bound to a service account by default and restricted to calling only the Gemini API, and unrestricted standard keys will be rejected.

API key security management illustration

OpenAI and Google prescribe the same rotation order: create a replacement key → deploy → verify it works → revoke the old key. The key is to rehearse this on a calm day first, figuring out exactly where the key lives—production, preview environments, CI, that cron job nobody remembers—rather than discovering a missed spot under incident pressure.

Both also offer workload identity federation: on supported cloud workloads, short-lived tokens replace stored keys—essentially "rotation where there's nothing to rotate."

Workload identity federation is the mainstream alternative to long-lived secrets. The basic mechanism: a cloud platform (such as AWS, GCP, or Azure) issues short-lived identity tokens to running workloads, the model provider trusts that identity provider, and the token is exchanged directly for temporary access credentials. Throughout the process, there is no static key that needs to be written into environment variables or config files, and therefore no window for "long-term abuse after a leak." It's not that rotation is eliminated entirely—rather, rotation is shifted from a manual operation to something the platform does automatically: tokens expire and become invalid, and new tokens are obtained automatically by the runtime. For services already running in the cloud, this is one of the highest-priority changes to make.

Hard spending limits, not alerts

The OpenAI article puts it bluntly: "Spending alerts alone cannot stop API traffic." Getting an email at 3 a.m. is just a receipt for money already spent.

ProviderHard limitCaveats from the docs
OpenAIOrganization- or project-level monthly spending limit, enforcedEnforcement isn't instantaneous; the hard limit may also block legitimate requests
AnthropicWorkspace-level monthly spending limit, below the organization limitCannot be set on the Default Workspace
GoogleAI Studio project monthly spending limit, plus tiered limits per billing accountExperimental feature with about a 10-minute delay; batch jobs and agent sessions can overspend

Auto-recharge works the same way. Anthropic's key best practices treat the auto-recharge cap as a safeguard against leaked keys, and Google's Prepay plans also have a monthly auto-charge limit. Auto-recharge without a limit is a credit card without a limit.

Teams building their own agents should also add a gate at the code layer. The open-source project Claient does this: when an account uses the platform key, a webhook atomically reserves budget before each conversation turn and stops responding once the monthly cap is reached. This kill-switch idea applies equally to self-built agents.

Keys belong only on the server

OpenAI and Google are both explicit: don't put keys in browser or mobile code—route calls through your backend.

In Next.js, the dividing line is the NEXT_PUBLIC_ prefix. At build time, Next.js inlines values with this prefix into the JavaScript bundle—an LLM key with NEXT_PUBLIC_ is a key that has already been published.

The correct approach is to use the server-only package for compile-time protection:

// lib/llm.ts
import 'server-only'; // Importing from a client component causes the build to fail outright
import Anthropic from '@anthropic-ai/sdk';

export const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

Backend routes also need authentication and rate limiting. A public route that forwards requests on your behalf is still using your key:

// app/api/chat/route.ts
import { anthropic } from '@/lib/llm';

export async function POST(req: Request) {
  // Do authentication and rate limiting first
  const { message } = await req.json();
  const res = await anthropic.messages.create({
    model: MODEL,
    max_tokens: 512,
    messages: [{ role: 'user', content: message }],
  });
  return Response.json(res.content);
}

If your backend has a fixed egress IP, add an IP allowlist on top. OpenAI's IP allowlist applies at the organization or project level; non-allowlisted IPs receive a 401 ip_not_authorized even with a valid key. Google lets you restrict keys to specific IPs under Application restrictions in the Cloud console. Anthropic offers IP allowlisting to enterprise customers through support channels.

The reason the NEXT_PUBLIC_ prefix is dangerous has to do with Next.js's build model. During the build phase, Next.js replaces variables in process.env that start with that prefix directly with their literal values in the client bundle—there's no runtime step where "the server reads the environment variable and sends it down." This means that once you add the prefix, the secret appears in plaintext in a JavaScript file the browser can download, and anyone who opens developer tools or fetches static assets can grab it. By contrast, the server-only package uses an entry module that throws an error in client environments to move this constraint to compile time: as long as a server module is imported by a client component, the build fails—rather than discovering after launch that the key shipped with the bundle.

Think carefully before pasting a key into a hosted dashboard

The Anthropic Help Center has the most honest line: when you upload an API key to a third-party tool, "you're handing that tool's developer access to your Claude Console account." This isn't a comment on OpenCode—it's a shared property of all hosted tools that use your key to call models. Moreover, deleting a key in a tool does not revoke it—only the provider can revoke it.

Claient accepts customer-supplied Claude keys (BYOK), so its author happens to be on the other side of this. Its implementation: keys are stored in Supabase Vault, and the settings table keeps only the secret's id; the function that can return the decrypted key can only be executed by the service_role used by the webhook, so no dashboard user (including the owner) can read it back, and the UI never displays it again. If a customer's key is revoked, the bot falls back to the platform key and notifies the merchant rather than failing silently. This limits what a dashboard vulnerability could expose, but it doesn't make the key unstealable if the server is compromised—no solution can do that.

From the user's side, the actionable advice is: give each hosted tool its own dedicated key, placed in a separate project or Workspace, with a low cap and an expiration time—and ask the vendor three questions: where is the key stored, is it encrypted, and who can decrypt it?

The first hour after a leak

  1. Revoke on the provider side, not by deleting in the tool. OpenAI recommends rotating immediately from the API Keys page; in Claude Console, Disable is reversible and Delete is permanent. If a key is actively being abused, revoke first and accept a few minutes of downtime. "Create first, delete later" is only for planned rotations.
  2. Issue a replacement key properly. Put it in the correct project or Workspace, set an expiration, and deploy it everywhere the old key appeared.
  3. Review usage by key, going back to the earliest date the key could have leaked—not just today.
  4. Lower spending limits during the investigation.
  5. Find the leak point before fixing it. Git history (deleting a file in a later commit is not the same as removing it), CI and error logs, any tool you've pasted it into.
  6. Contact billing support with the key ID, dates, and what happened. The OpenAI article points to help.openai.com.

FAQ

Can spending alerts protect a leaked API key?

No. Alerts only tell you money is being spent—they don't stop it. You need hard limits: OpenAI's enforced spending limit, Anthropic's Workspace spending limit, Google AI Studio's project spending limit. None are instantaneous, but they turn an open-ended bill into a bounded one.

Is it safe to paste an API key into a third-party tool?

It's only safe if you're comfortable handing your provider account to that vendor, because that's effectively what you're doing. If you do it, give it a dedicated key in a separate project or Workspace with a low cap and an expiration time. Deleting the key in the tool does not revoke it.

How do I rotate an Anthropic API key?

Create a new key in Claude Console with an expiration time, deploy it everywhere the old key was used, and once confirmed working, disable (reversible) or delete (permanent) the old key. The expiration is chosen at creation time and cannot be changed afterward.

There's nothing exciting about this setup, and that's exactly the point: boring default settings are what keep someone else's security incident in the news rather than on your bill.

#API key security#OpenAI API key#Claude API key#Gemini API key#key rotation#spending limits#BYOK#server-side security#Next.js server-only#workload identity federation
Share:

Related articles