API Authentication & Secrets
The key that gates a whole budget
LLM and vector API secrets must be created, stored, rotated and scoped as carefully as any credential. Keys in env vars, per-service keys, short-lived tokens and auditability are non-negotiable in production AI.
What you will learn
- Store and inject API keys without ever committing them
- Scope keys per team/service with least privilege
- Rotate and audit keys on a schedule
What is this?
API authentication for AI systems usually means bearer tokens — an API key sent in an Authorization header. Production discipline around them: keys never appear in code or git, they are injected via secrets managers or environment variables, each service gets its own scoped key, and they rotate on schedule. A leaked model key isn't just an auth breach — it's a budget and compliance breach.
Why do you need it?
- One leaked key can be scraped into an attacker's billable mining operation within minutes.
- Per-service keys let you revoke one leak without a global panic.
- Scopes cap blast radius: a read-only embeddings key can't spin up expensive generations.
- Audit logs tie every model call to a key, which is how you catch abuse early.
Mental model
A hotel key card per floor
Scoped API keys
You never hand every guest a master key. Each person gets only the floors they need, the card expires, and every entry is logged. API keys should behave the same.
How it works
- Secrets never ship: a vault (or Vercel env vars / a secrets manager) injects keys into runtime via environment variables.
- The client reads `os.environ` (or the platform's env store) and sets the Authorization header at request time.
- Providers issue scoped keys — read-only, per-project, with quotas — and log usage per key.
- Rotation replaces keys on a schedule; old keys are retired after a grace or expiry period.
- Audit dashboards expose per-key usage so abnormal spend surfaces immediately.
Secrets lifecycle.
Examples
Key injection without secrets in code
import os client = ModelClient( api_key=os.environ["MODEL_API_KEY"], base_url=os.environ.get("MODEL_BASE_URL"),) resp = client.chat.completions.create(messages=[{"role": "user", "content": "hi"}])The key is read from the environment at runtime. Nothing about it lives in the repository, and the base URL is config so you can point at a gateway in prod.
In production
- A CI pipeline injects test keys only into ephemeral environments, never into build logs.
- An org issues one read-only embeddings key per team and deletes it on team offboarding.
- A billing dashboard flags 3x spend on any key and the incident page traces calls to audit logs.
Best practices
- Use environment variables or a secrets manager; forbid keys in code, logs, or client bundles.
- Issue per-service keys with scopes matching the minimum privilege needed.
- Set rotation cadence and automate it; never 'rotate later'.
- Audit key usage; alert on spend anomalies and new key issuance.
Common mistakes
- Committing a key once — even in a removed commit, it lives in git history.
- Using one org key for everything, so any leak is catastrophic and revocable only globally.
- Embedding keys in frontend code where any client can extract them.
- Rotating without a grace window, breaking live services at 3am.
Common issues
401 Unauthorized on every callWrong key value, missing Authorization header, or rotated-but-still-cached key
Verify the env var value, the header construction, and that the deployed process reloaded env.
Key leaked into a public repoSomeone hardcoded it and pushed; git history now contains it
Rotate immediately, remove and purge history (carefully), add secret scanning to CI.
A key dollar-spend spikes 5xAbuse or a runaway retry loop burning tokens
Revoke the key, trace audit logs, and cap retries/spend at the gateway.
Debugging tips
- 401s after a rotation usually mean a stale env var on the running process — restart/redeploy.
- Check whether a proxy rewrote the Authorization header in the logs.
- If a key appears in a trace, strip it from the logging layer immediately, then rotate.
- Audit 'who issued this key, when, from where' before blaming the network.
Interview checkpoint
Hands-on lab
- Read API keys from env vars without hardcoding
- Inspect outgoing Authorization headers safely (redacted)
- Simulate rotation and confirm the server honors the new key
Build a Keyless Auth Inspector
25 min · intermediate
Quick quiz
Where should API keys live in a production system?
Sharing one org-wide key across services is good practice.