Anthropic API Key Security: Proxying, Workspaces and Rotation

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D7 API Key and Credential Handling

👋 In plain words: Your Anthropic API key is a password that spends money and reaches your data. If it ends up in a browser, a mobile app, a Git commit or a log, someone else can use it. This lesson shows how to keep keys on the server, give each environment its own key, catch leaks before they ship and rotate keys without downtime, one step at a time.

Advertisement

The CCDV-F exam expects you to handle Anthropic API keys correctly in development and production: server-side proxying rather than client embedding, workspace-scoped keys versus admin keys, environment separation, rotation and access monitoring, without exposing any key beyond its intended scope. In this lesson you will build a small FastAPI proxy so the browser never sees a key, write a secret scanner for your repository, plan per-environment keys and workspaces, and rotate a key safely.

📖 What You’ll Learn: You will be able to keep keys server-side with a proxy, choose between workspace keys and admin keys, separate keys per environment, detect leaked keys, and rotate and monitor keys.

🔑 Key terms

  • API key: a secret (starting sk-ant-) that authenticates requests to the Claude API and bills your organisation.
  • Workspace: a sub-division of a Claude Console organisation with its own keys, limits and usage reporting.
  • Admin API key: a separate key type (starting sk-ant-admin) for organisation administration through the Admin API, not for calling models.
  • Proxy: your server endpoint that calls Claude on behalf of clients, holding the key itself.
  • Rotation: replacing a key with a new one and revoking the old one.

🪜 Step 1: Never put a key in a client

Anything shipped to a browser, mobile app, desktop app or public repository can be extracted. That includes environment variables baked into front-end builds. The rule: only your server holds the key.

Where Key allowed?
Browser JavaScript, mobile and desktop apps No
Front-end build variables (NEXT_PUBLIC_…, VITE_…) No
Your backend server or serverless function Yes, from a secrets manager or environment
CI jobs Yes, from CI secrets
Git, tickets, chat, screenshots, logs Never
Advertisement

🪜 Step 2: Build a server-side proxy

The browser calls your endpoint; your server checks the user and calls Claude with its own key. The proxy also lets you enforce limits per user, choose the model, and log usage:

📄 proxy.py

import os

import anthropic
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

app = FastAPI()
client = anthropic.Anthropic()  # key comes from the server's environment / secrets manager
USERS = {"token-alice": "alice"}  # demo: your real app uses its normal login/session
QUOTA = {"alice": 3}


class Ask(BaseModel):
    question: str


@app.post("/api/ask")
def ask(body: Ask, authorization: str = Header(default="")):
    user = USERS.get(authorization.removeprefix("Bearer "))
    if not user:
        raise HTTPException(401, "sign in first")
    if QUOTA[user] <= 0:
        raise HTTPException(429, "daily limit reached")
    QUOTA[user] -= 1
    r = client.messages.create(model="claude-opus-5-5", max_tokens=300,  # model chosen server-side
                               messages=[{"role": "user", "content": body.question[:2000]}])
    return {"answer": r.content[0].text, "remaining": QUOTA[user]}

📄 test_proxy.py

from fastapi.testclient import TestClient

from proxy import app

browser = TestClient(app)

ok = browser.post("/api/ask", json={"question": "What is a smoke test?"}, headers={"Authorization": "Bearer token-alice"})
print(ok.status_code, ok.json())
print(browser.post("/api/ask", json={"question": "hi"}).status_code, "<- no login")
print("response contains a key?", "sk-ant" in ok.text)

⌨️ Terminal

python test_proxy.py

🖥️ Output (sample run)

200 {'answer': 'A quick check that the most important features work before deeper testing.', 'remaining': 2}
401 <- no login
response contains a key? False
  • The browser only ever sees your endpoint and its JSON. The key never leaves the server.
  • The server decides the model, max_tokens and input length, so a client cannot turn your key into an expensive general-purpose API.
  • Add your normal authentication, rate limits and logging here.

🪜 Step 3: Choose the right key type and scope

  1. Workspace-scoped API keys for applications. Create one per application and environment, in the right workspace, so usage and limits are separated and a leak affects only that scope.
  2. Admin API keys (sk-ant-admin…) only for automation that manages the organisation (members, workspaces, keys, usage reports). They cannot be used to call models, and they must never be deployed with an application.
  3. Give each key a clear name: checkout-bot-prod, checkout-bot-staging, ravi-laptop-dev.
⚠️ Watch out: Reusing one key across dev, staging and production means a laptop leak is a production incident, and you cannot rotate it without touching every environment at once. Separate keys and workspaces per environment.

🪜 Step 4: Separate environments

Environment Workspace Key Stored in
Developer laptops dev one per person local environment variable or keychain
CI ci one per pipeline CI secrets
Staging staging one per service cloud secrets manager
Production prod one per service cloud secrets manager, rotated on schedule

Workspaces let you set spending limits and see usage per environment, which also makes unusual activity easy to spot.

Advertisement

🪜 Step 5: Detect leaks before they ship

Scan the repository (and pre-commit) for key patterns. This scanner runs locally:

📄 scan_secrets.py

import re
from pathlib import Path

PATTERN = re.compile(r"sk-ant-(?:admin\d*-|api\d*-)?[A-Za-z0-9_\-]{8,}")

Path("demo").mkdir(exist_ok=True)
Path("demo/settings.py").write_text('ANTHROPIC_API_KEY = "sk-ant-api03-AbCdEfGh123456"\n')
Path("demo/app.js").write_text("const key = process.env.KEY; // ok\n")
Path("demo/.env.example").write_text("ANTHROPIC_API_KEY=\n")

findings = []
for path in Path("demo").rglob("*"):
    if path.is_file():
        for n, line in enumerate(path.read_text(errors="ignore").splitlines(), 1):
            if PATTERN.search(line):
                findings.append(f"{path.as_posix()}:{n}: possible Anthropic key")
print("\n".join(findings) or "no keys found")
raise SystemExit(1 if findings else 0)

⌨️ Terminal

python scan_secrets.py

🖥️ Output

demo/settings.py:1: possible Anthropic key
  • Run it (or an established secret scanner) as a pre-commit hook and in CI.
  • Commit an .env.example with empty values and keep the real .env in .gitignore.
  • Never print keys in logs; log the key name or workspace instead.

🪜 Step 6: Rotate, revoke and monitor

Planned rotation without downtime:

  1. Create a new key in the same workspace.
  2. Store it in the secrets manager and roll it out to all instances.
  3. Confirm traffic uses the new key (usage by key in the Console).
  4. Revoke the old key.

After a suspected leak: revoke the key immediately (accept a short outage), create a new one, then investigate: where it leaked, what it was used for (usage reports), and how to prevent it (scanner, proxy, scope).

Monitor usage per workspace and key for unusual spikes, unknown models or off-hours traffic, and set spend limits so a stolen key has a ceiling.

🎯 Exam focus: Credential scenarios usually have one clearly correct pattern: server-side proxy for any client-facing feature; workspace-scoped keys per application and environment; admin keys only for administration; immediate revocation after a leak; secrets managers and CI secrets, never code or front-end variables.

🌍 Real-world example: Ravi’s leaked key

A teammate pasted a code snippet with a real key into a public issue tracker. Because keys were separated, it was only the dev workspace key for one laptop. Ravi revoked it within minutes, checked the workspace usage (no unknown traffic), issued a new key, and added scan_secrets.py as a pre-commit hook for the whole team.

Advertisement

🧪 Practice Questions

Question 1. A team’s React app calls the Claude API directly from the browser using a key stored in a front-end build variable. What should they do?

  • A. Obfuscate the key in the JavaScript bundle
  • B. Move the call to a server-side proxy that holds the key and authenticates users
  • C. Use an admin key instead
  • D. Rotate the key weekly and keep the design
Show answer

Answer: B. Anything shipped to the browser can be extracted. Only a server should hold the key.

Question 2. Which key should a production chatbot use to call Claude?

  • A. A workspace-scoped API key created for that application and environment
  • B. An Admin API key
  • C. A developer’s personal key
  • D. The same key used by CI
Show answer

Answer: A. Applications use scoped API keys per environment; admin keys are for organisation administration only.

Question 3. A key appears in a public commit. What is the first action?

  • A. Delete the commit and hope nobody saw it
  • B. Revoke the key immediately, then issue a new one and investigate usage
  • C. Wait for the next scheduled rotation
  • D. Change the key’s name
Show answer

Answer: B. Leaked keys can be found by scanners within minutes. Revocation stops misuse; history rewriting does not.

Question 4. Which two practices limit the damage of a single leaked key? (Choose 2.)

  • A. Separate keys and workspaces per environment and application
  • B. One shared key for all services
  • C. Spend limits and usage monitoring per workspace
  • D. Printing keys in debug logs for traceability
Show answer

Answer: A and C. Scoping limits what one key can reach, and limits plus monitoring cap and reveal misuse.

📝 Assignment

  1. Task 1: Search your projects for places where a key could reach a client (front-end variables, mobile config).
    ✅ Done when: every client-side Claude call goes through a server endpoint.
  2. Task 2: Add scan_secrets.py (or a standard secret scanner) as a pre-commit hook.
    ✅ Done when: committing a file with a fake sk-ant- key is blocked.
  3. Stretch: Write a rotation runbook for your team with the four steps from Step 6, the owners, and how to confirm the old key has no traffic.
    ✅ Done when: a teammate could follow it without asking questions.
Advertisement

❓ Frequently Asked Questions

🤔 Can I use the Claude API directly from a browser?

Do not put your API key in a browser or mobile app. Call your own server endpoint, which holds the key and calls Claude.

🤔 What is the difference between an Anthropic API key and an Admin API key?

API keys call the Claude API for models. Admin API keys manage the organisation (members, workspaces, keys, usage) through the Admin API and cannot call models.

🤔 How often should I rotate API keys?

On a regular schedule set by your security policy, whenever someone with access leaves, and immediately after any suspected leak.

🤔 How do I keep Claude API keys out of Git?

Use environment variables or a secrets manager, commit only an empty .env.example, Git-ignore .env, and run a secret scanner in pre-commit and CI.

🏁 Summary

  • Only servers hold keys; clients call your proxy.
  • The proxy controls model, limits and authentication per user.
  • Use workspace-scoped keys per application and environment; admin keys only for administration.
  • Scan for secrets in pre-commit and CI; never log keys.
  • Rotate on schedule, revoke immediately after leaks, and monitor usage with spend limits.
📝 Test yourself: D7 Security and Safety practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with FastAPI with Claude: Build a Production-Ready AI Service.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.