AI API Key Security & Anti-Abuse Guide: Proxies, Rate Limits & Spend Caps
Protect free tiers and billed accounts from credential leaks with server-side proxies, model allowlists, per-IP rate limits, and hard spend caps.
Automated bots continuously scan public Git repositories and client-side JavaScript bundles for leaked AI API keys. Within minutes of exposure, a free quota is wiped out — and if a credit card is attached for trial verification, an attacker can run up hundreds of dollars in unauthorized completions.
1. Four Most Common Credential Leak Paths
- Public Frontend Env Prefixes: Putting a secret in
VITE_*orNEXT_PUBLIC_*compiles the plaintext key directly into browser bundles. - Git Commit History: Deleting
.envin a follow-up commit does not erase it from earlier commits; scanners index public pushes within seconds. - Unredacted Logs & Error Responses: Echoing upstream request headers in HTTP 500 error responses or sharing unredacted curl commands in public issues.
- Shared Master Keys: Reusing one root key across local dev, CI, and production prevents isolated revocation.
2. Standard Security Architecture for Public Apps
Always route traffic through Browser → Your Backend Proxy → AI Provider and enforce four checks on your server:
- Per-IP / Per-Session Rate Limits: Cap burst and daily calls per visitor.
- Strict Payload Caps: Reject oversized request bodies (e.g., > 8 KB) before forwarding to prevent TPM exhaustion attacks.
- Server-Side Model Allowlist: Never forward a client-supplied
modelstring verbatim — an attacker can swap a free Flash model for an expensive frontier model. - Global Daily Kill Switch: Track cumulative
usage.total_tokensand gracefully pause public access when the daily cap is reached.
3. Mandatory Provider Console Safeguards
On any account with a payment method on file, configure a hard monthly spend limit (not just email alerts, which do not stop traffic) and issue separate scoped keys per environment.
4. Free-Tier Data Privacy Checklist
Before sending prompts to a free tier or third-party relay, scrub customer PII (replace emails, phone numbers, and IDs with reversible placeholders locally), never upload private credentials, and move confidential codebases to offline local Ollama models.