To protect AI API keys from theft, keep credentials out of source code and client-side applications, store them securely, restrict access, scan repositories for exposed secrets, and monitor API usage. If a key leaks, revoke it or rotate it at the issuing provider, investigate unauthorized activity, and replace it safely.
An AI API key can give another person access to your account’s model usage and available quota. Depending on the provider and credential type, a compromise can lead to unexpected charges, exhausted limits, data exposure, or access to other cloud resources.
The threat is no longer limited to developers accidentally publishing keys on GitHub. In its September 8, 2026 report, Google Threat Intelligence Group described an April intrusion in which an exposed GitHub personal access token helped an attacker access a cloud environment, deploy unauthorized AI infrastructure, and create a privileged service account. The incident shows why protecting AI credentials also requires protecting the systems and identities around them. Read the Google Threat Intelligence report.
The following nine steps provide a practical security plan for developers, AI application owners, and small security teams. You can apply the relevant controls whether your application uses OpenAI, Anthropic, Google Gemini, or another AI provider.
1. Inventory Every AI API Key and Credential
You cannot protect credentials that you do not know exist. Start by identifying every AI API key, access token, service account credential, and developer-tool secret used by your applications and workflows.
Check these locations:
- Application configuration and environment files.
- Local developer machines and project folders.
- Git repositories, including older commits and branches.
- CI/CD platforms and deployment settings.
- Cloud environments, containers, and serverless applications.
- AI coding assistants and third-party developer tools that have been granted access to credentials.
Create a simple credential inventory with the provider, application, owner, environment, permissions, storage location, and expiration or rotation arrangements. Never place the actual secret value in the inventory.
This record helps you identify unused credentials, understand which applications depend on a particular key, and determine whom to contact when a leak occurs. Treat authentication tokens and session credentials as secrets too; an API key inventory alone will not cover every route to unauthorized AI access.
2. Remove API Keys from Source Code and Repositories
Never hardcode a private AI API key in application source code or commit it to a Git repository. A public repository makes exposure obvious, but a private repository is not a secure credential store.
Keep API requests that require private credentials on a trusted backend. Browsers and mobile applications cannot reliably keep a long-lived secret confidential because users can inspect client-side code, application packages, or network behavior.
For local development, use an environment variable rather than writing the secret directly into your source files. For example, an application can read an OpenAI key from a variable named OPENAI_API_KEY instead of embedding the key in its code.
import osfrom openai import OpenAIclient = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
This example keeps the literal key out of the source file. It does not automatically make the environment secure: the variable still needs to be protected from unauthorized processes, logs, debugging tools, and compromised accounts.
Also add local secret files, such as .env, to .gitignore where appropriate. Check that the file is not already tracked by Git, and do not assume .gitignore removes files or secrets that were committed previously.
OpenAI’s API key safety guidance recommends keeping keys out of client-side environments and repositories.
3. Store AI Credentials in a Secrets Manager
Environment variables are useful for local development and some deployments, but a dedicated secrets manager generally provides stronger centralized access control, auditing, and secret lifecycle management for production applications.
A secrets manager stores sensitive values separately from application code and lets authorized workloads retrieve them. Examples include Google Cloud Secret Manager, AWS Secrets Manager, Azure Key Vault, and HashiCorp Vault.
Choose the storage method according to the application and deployment environment:
| Storage method | Best fit | Main limitation |
|---|---|---|
| Local environment variables | Developer workstations and simple development setups | Can be exposed by compromised processes or unsafe debugging |
| Encrypted CI/CD secrets | Build and deployment workflows | Access to the pipeline or its runners may expose secrets |
| Dedicated secrets manager | Production applications and teams managing multiple credentials | Requires secure access configuration and operational maintenance |
| Workload identity | Supported cloud workloads and compatible AI providers | Availability and setup differ by provider and environment |
For production, give the application permission to retrieve only the secrets it needs. Avoid giving every developer or deployment pipeline unrestricted access to all credentials.
Google Cloud’s Secret Manager best practices explain how to limit secret access, separate environments, use workload identity, and audit secret access.
One important distinction: encrypting a secret at rest does not protect it from an application or identity that is authorized to retrieve it. Access controls and runtime security still matter.
4. Apply Least Privilege and Separate Development From Production
Every credential should have the minimum permissions needed for its intended job. If a development key is compromised, it should not automatically provide access to production systems or unrelated cloud resources.
Start with these controls:
- Use separate credentials for development, testing, staging, and production.
- Give each developer or application its own credential where the provider supports it.
- Apply available key restrictions, project permissions, and role-based access controls.
- Restrict API access to approved IP addresses or networks when supported and practical.
- Remove credentials that are no longer used.
- Review who can create, view, rotate, and revoke secrets.
For example, a test application should not use the same credential as a customer-facing production service. Separate keys make it easier to identify which environment is generating requests and revoke one credential without unnecessarily disrupting another.
Provider capabilities vary. OpenAI supports individual API keys and configurable permissions, while Google Cloud provides API key restrictions and IAM-based authentication options. Check the official documentation for the exact API and authentication method you use.
A useful rule is to limit both what a credential can access and where it can be used. A key restriction is not a substitute for secure storage, but it can reduce the damage if the key is stolen.
5. Use Short-Lived Credentials Where Supported
Long-lived secrets create an ongoing risk because a stolen credential may remain useful until someone revokes it. Short-lived credentials reduce the period during which an exposed credential can be used.
Where supported, consider workload identity federation or another identity-based authentication method. A trusted workload proves its identity and obtains a temporary credential instead of storing a permanent secret that must be copied into its configuration.
Before adopting this approach, verify three things:
- The AI provider supports the relevant identity mechanism for your workload.
- Your deployment platform can securely establish the required identity.
- The resulting identity has only the permissions needed for the application.
OpenAI documents workload identity federation for supported workloads. Google Cloud also recommends identity-based methods for appropriate cloud resources rather than relying on exported service account keys.
Do not assume that every AI API supports short-lived authentication. Some integrations still require conventional API keys. In those cases, protect the key through secure storage, restricted access, monitoring, and a documented rotation process.
6. Enable GitHub Secret Scanning and CI/CD Protection
Developers can accidentally commit API keys even when they understand the risks. Automated scanning helps catch those mistakes before they become incidents.
GitHub secret scanning can identify supported credentials in repository history, while push protection can block supported secrets from being pushed in the first place when the feature is enabled and applicable.
A practical setup includes:
- Enable GitHub secret scanning where available.
- Enable push protection for supported secret types.
- Scan existing repositories and historical commits.
- Add secret scanning to CI/CD workflows.
- Review alerts and investigate suspected exposures promptly.
- Limit who can bypass protection and document exceptions.
GitHub’s secret scanning documentation explains its detection capabilities. Its secret remediation guide explains how to respond to exposed credentials.
Tools such as Gitleaks can also help detect secrets in repositories and development workflows.
No scanner catches every possible secret. Detection depends on supported patterns, configuration, repository coverage, and the types of credentials involved. Continue using secure storage and access controls even when scanning is enabled.
7. Rotate and Revoke Exposed API Keys Immediately
If an AI API key has been exposed, treat it as compromised until you have confirmed that it is no longer usable.
The immediate response is to invalidate the credential at the provider. Deleting the visible key from a source file, GitHub commit, or repository history does not make the original credential safe.
Follow this sequence:
- Identify the exposed credential and the provider that issued it.
- Revoke the key immediately if the application can tolerate the interruption.
- If service continuity is essential, create a replacement with appropriate permissions, switch the application to the new key, verify that it works, and revoke the old key promptly. Do not leave the exposed key active longer than necessary.
- Investigate usage logs and account activity for signs of unauthorized access.
- Remove exposed copies from source code, configuration files, logs, and repository history where appropriate.
- Check whether the incident exposed other credentials or affected related accounts.
After containment, update the credential inventory and review why the key was exposed. The fix should address the original cause, whether that was a code commit, overly broad access, an insecure developer device, or a third-party integration.
See GitHub’s official leaked-secret remediation guidance for more details.
8. Monitor AI API Usage, Logs, and Billing
A stolen credential may be used before a developer or security team notices the exposure. Monitoring helps identify suspicious activity and provides evidence for an investigation.
Review the usage and audit information available from your AI provider and hosting platform. Look for unusual request volumes, unfamiliar usage patterns, unexpected quota consumption, new identities, or activity that does not match your application’s normal behavior.
Configure the following where supported:
- Usage and billing alerts.
- Project or organization spending limits.
- Hard enforcement limits when appropriate.
- Rate limits and quotas.
- Authentication and administrative audit logs.
- Alerts for unusual cloud resource creation or permission changes.
Understand the difference between a spending alert and a hard limit. An alert tells you that usage has crossed a threshold; it does not necessarily stop additional requests. Hard enforcement may block further usage, and some systems may not apply limits instantly.
For example, OpenAI recommends reviewing usage, establishing spending limits, and using hard enforcement where appropriate. Its documentation also warns that enforcement is not instantaneous and spending may slightly exceed a configured limit.
Monitoring is most effective when you establish a baseline for normal usage. A sudden increase is a useful signal to investigate, but unusual activity is not automatically proof of credential theft.
9. Test Your Incident-Response Plan and Audit Access Regularly
Security controls are only useful if your team knows how to operate them during an incident. Test whether you can revoke a credential, deploy a replacement, identify its owner, and restore the application without unnecessary downtime.
Schedule regular reviews of credential ownership, permissions, unused keys, secret-manager access, scanning alerts, and monitoring rules. Include a practical incident exercise so the people responsible for the application understand their roles.
Document:
- Who can revoke each credential.
- How the application receives its replacement.
- Which services depend on the credential.
- Where to review usage and audit logs.
- Who should be notified when a compromise is suspected.
- How to verify that the exposed credential is no longer accepted.
The review interval should reflect the sensitivity of the system, the rate of change, and the organization’s risk. Review access after staff departures, major deployments, permission changes, and security incidents rather than relying solely on a calendar.
What to Do When an AI API Key Is Compromised
Use this response matrix to choose the immediate action based on the incident you are facing.
| Situation | Immediate response | Next action |
|---|---|---|
| A key appears in a public GitHub repository | Revoke it at the issuing provider | Replace the key, investigate usage, and clean up exposed copies |
| A developer’s device may be compromised | Contain the device and revoke credentials that may have been accessed | Investigate related tokens, sessions, accounts, and stored secrets |
| Unexpected AI API charges appear | Restrict or revoke the suspected credential and contain unauthorized access | Review usage logs, secure associated accounts, and investigate billing |
| A secret scanner reports an exposed key | Treat an active exposed credential as compromised | Revoke or rotate it, then resolve the alert and address the source of exposure |
Do not delay revocation while attempting to rewrite Git history or remove every copy of the secret. Containment comes first; repository cleanup and investigation follow.
If the incident involves a broader cloud account, privileged service account, or compromised developer identity, secure those related access paths too. Replacing a single API key may not be enough to contain the full incident.
AI API Key Security Checklist
Use this checklist to verify your current setup.
Implementation progress
[ 1] Inventory AI API keys, tokens, and service-account credentials
[ 2] Keep private keys out of source code, browsers, and mobile applications
[ 3] Store production secrets in an appropriately secured system
[ 4] Separate development and production credentials
[ 5] Apply least privilege and supported key restrictions
[ 6] Use short-lived credentials or workload identity where supported
[ 7] Enable repository secret scanning and push protection
[ 8] Document and test credential revocation and replacement
[ 9] Monitor API usage, quotas, billing, and relevant audit logs
[ 10] Review credential ownership and access regularly
FAQs: How to Protect AI API Keys from Theft
Are environment variables enough to protect AI API keys?
Environment variables are safer than hardcoding keys in source files, but they are not a complete security solution. A compromised process, unsafe debugging endpoint, or misconfigured logging system may expose them. For production workloads, consider a dedicated secrets manager or identity-based authentication where supported, and restrict access to the processes that need each credential.
Should every application have its own API key?
Where the provider supports it, use separate credentials for different applications and environments. This improves accountability and makes it easier to revoke a compromised key without disrupting unrelated services. Give each credential only the permissions it needs, and avoid sharing a single production key across developers, testing environments, and multiple applications.
How often should AI API keys be rotated?
There is no universal rotation interval that suits every AI provider and application. Follow the provider’s guidance and your organization’s risk requirements. Rotate immediately when a key is exposed, when access is no longer justified, or when a relevant compromise is suspected. Automated rotation can help, but test replacement and revocation procedures to avoid service interruptions.
Can deleting a leaked API key from GitHub make it safe?
No. Removing the key from a commit or rewriting repository history does not invalidate the credential. Anyone who copied the key may still be able to use it while it remains active. Revoke or rotate the credential at the issuing provider first, investigate possible misuse, and then clean up the repository and other exposed copies.
Can a stolen AI API key lead to unexpected charges?
Yes. If an attacker can use a stolen credential to submit requests against your account, those requests may consume your quota or generate charges. The extent of the impact depends on the provider, account permissions, usage limits, and enforcement settings. Monitor usage, configure available spending controls, and revoke suspected compromised credentials promptly.
Protect Your AI Credentials Before an Incident
Start by identifying where your AI credentials live, then remove them from code and apply access controls appropriate to each workload. Make sure you can revoke a key quickly, identify suspicious usage, and restore your application with a replacement.
For implementation details, use the official OpenAI API key safety guide, Google Cloud API key guidance, and GitHub secret-scanning documentation. These resources help you adapt the controls to the providers and development tools your team actually uses.
Belayet Hossain is a Senior Tech Expert and Certified AI Marketing Strategist. Holding an MSc in CSE (Russia) and over a decade of experience since 2011, he combines traditional systems engineering with modern AI insights. Specializing in Vibe Coding and Intelligent Marketing, Belayet provides forward-thinking analysis on software, digital trends, and SEO, helping readers navigate the rapidly evolving digital landscape. Connect with Belayet Hossain on Facebook, Twitter, Linkedin or read my complete biography.