Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. AI Security

Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It

A chat widget with the Claude key in its bundle, and one key shared by dev, staging and prod. Fix both: a small FastAPI proxy that holds the key and returns 503 without it, a scoped key per environment, rotation in the right order, and what to do the day a key leaks.

Chaand Sheikh

·27 November 2026AI Security

What you will learn

  • Move a Claude API key out of the browser into a server-side proxy that fails closed
  • Give each environment its own workspace-scoped key and know what an admin key can do
  • Rotate a key in the safe order and watch usage per key
  • Respond to a leaked key: disable it, issue a new one on the server, and cap each session

Before you start

  • The Claude Messages API: your first call
  • Basic FastAPI

Someone says: ship the chat widget today. The quick version calls Claude straight from the page, with the API key inside the front-end bundle. Anyone who opens the page can read the code behind it.

In this article we keep the key where it belongs: a server-side proxy, one key per environment, rotation, and usage per key. Then we look at the day the key leaks anyway. The code runs against a stand-in for the Messages API, with a test value as the key, so no real key is ever used.

Two ways to lose control of a key

  1. The key sits in the browser bundle. Anyone can copy it and spend on your bill.
  2. One shared key for dev, staging and prod. A test script leaks it, you switch the key off, and prod goes down with it.

Think of a hotel. The master key stays behind the desk. Each room gets its own key card. A lost card is switched off and a new one is cut. And the desk log shows which card opened which door. The guest never holds the master key, and the browser never holds the API key.

A server-side proxy

The browser knows our address, only the server knows the key Browser no key Our server key from env Claude API POST /chat new request reply text only Browser headers are not passed on. No key: 503, and no call is made.
The proxy pattern: the key lives in the server's environment.

Calling Claude straight from the browser is a cross-origin request. It's refused without a special opt-in header, and even then the key would sit in the page. So the browser talks to us, and we talk to Claude.

proxy.py

"""Our server. The browser calls /chat. Only this server holds the key."""
import os
from anthropic import Anthropic
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import stand_in

app = FastAPI()
MODEL = "claude-sonnet-5-5"


class Ask(BaseModel):
    message: str


def claude():
    # The key comes from the environment, never from the browser.
    key = os.environ.get("ANTHROPIC_API_KEY")
    if not key:
        raise HTTPException(503, "server has no API key")
    return Anthropic(api_key=key, http_client=stand_in.http_client())


@app.post("/chat")
def chat(ask: Ask):
    client = claude()
    # A new request to Claude: browser headers are not passed on.
    reply = client.messages.create(
        model=MODEL,
        max_tokens=300,
        messages=[{"role": "user", "content": ask.message}],
    )
    return {"reply": reply.content[0].text}
  • The key comes from the ANTHROPIC_API_KEY environment variable on the server.
  • If it's missing, the proxy fails closed with status 503.
  • The browser sees one endpoint, /chat. Each message becomes a new request to Claude, so browser headers aren't forwarded.
  • Only the reply text goes back. In production you'd drop the http_client argument; here it points the real SDK at the stand-in.

One message through it

The run uses FastAPI's TestClient as the browser, with an Origin header set, and the test value test-key-from-env as the key.

1 browser -> our server  POST /chat
  key in browser request: no
2 our server -> Claude  POST /v1/messages
  key from env, sent as Authorization Bearer: True
  browser Origin passed on: False
3 reply to browser: 200 test model reply: your order ships on Monday.
4 keys in client code: 0
5 key missing: 503 server has no API key
  calls to Claude: 0

A key for one workspace, or an admin key

Workspace-scoped API keyAdmin key
ReachesOne workspaceThe whole organization
DoesCalls Claude from one appManages members, workspaces and keys; pulls usage and cost reports
Admin APICan't use it at allThat's what it's for
WhoEach app, each environmentOrganization admins only, never in an app

You choose the scope when you create a key. Member roles and admin keys come with a team organization.

One key per environment, and rotation

In the Claude Console the lecture uses a workspace called ci-demo with three API keys: prod, staging and dev, each scoped to that workspace. The API keys page notes that a key acts as the user or service account it was created for.

Rotation goes in this order:

  1. Create the new key (prod two) and deploy it first.
  2. Then disable the old prod key. Disable can be undone; delete is permanent.
  3. Watch the Usage page, filtered by API key. A retired key that's still busy shows up there.

The Console also has a Cost page with the same API key filter, a monthly spend limit for the organization with optional limits per workspace (the organization limit still applies), rate limits shown per model and set by the organization's tier, and an IP allowlist under Security, marked Beta at the time of recording.

For production, the docs prefer a service account, a named non-human identity, over a key that acts as a person. A service account can also be the target of workload identity federation: the workload trades a token from your identity provider for a short-lived one, so there's no stored key at all.

The day a key leaks

Now the scenario. A support app calls Claude directly, so the key is inside the shipped build. A stranger posts it online and usage climbs. A scan of the build finds it:

== 1. The key in the client build
line 3: key-shaped text sk-ant-EXAM...

Disable the leaked key and make a new one. Then the app stops holding any key. It sends a session token and the text to your own proxy, and the proxy adds the key and sets the limits:

"""The Claude key lives here, never in a client."""
import os

SERVER_KEY = os.environ.get("CLAUDE_PROXY_KEY", "unset")
SESSIONS = {"sess-ana": "ana", "sess-ben": "ben"}
LIMIT = 3
used = {}


def handle(request):
    user = SESSIONS.get(request.get("session"))
    if user is None:
        return 401, "unknown session"
    used[user] = used.get(user, 0) + 1
    if used[user] > LIMIT:
        return 429, "too many requests"
    upstream = {
        "headers": {"x-api-key": SERVER_KEY},
        "max_tokens": 300,
        "text": request["text"][:500],
    }
    return 200, "forwarded, key added on the server"
== 2. Through the proxy
sess-ana  -> 200 forwarded, key added on the server
none      -> 401 unknown session
sess-ana  -> 200 forwarded, key added on the server
sess-ana  -> 200 forwarded, key added on the server
sess-ana  -> 429 too many requests

No session, no call. A per-user limit means a stolen session can't run up the bill. This is a tiny stand-in that builds the upstream request but doesn't send it.

Common mistakes

Tempting fixWhy it fails
Minify the bundleThe key is still in the page
Split the key into pieces in the appThe pieces still ship, and anyone can join them again
A request limit in the appThat's code the thief never has to run
One shared key, rotated weeklyStill shared between environments, still in the page
Lower the spend limitLimits the damage, not the leak
Wait for the key to expireThe stranger keeps spending until then

Watch for the words browser, front-end bundle or shared key. The answer moves the key to a server, and gives each environment its own.

Recap

IdeaIn one line
ProxyThe key stays on the server; the app holds a session at most
ScopeOne workspace-scoped key per environment; admin keys never in an app
RotateDeploy the new key first, then disable the old one, then watch usage per key
LeakDisable, reissue on the server, cap each session
KeylessWhere a workload has its own identity, skip the stored key

For local development, keeping the key in a .env file that never reaches git is covered in Set Up a Python AI Project with uv, VS Code and an API Key in .env. The other half of the leaked-key scenario, a ticket that tells the agent to delete a customer, is handled by a PreToolUse hook and least privilege.

Try it yourself

Extend proxy.py with the session check and per-user limit from the leaked-key proxy, so /chat returns 401 without a known session and 429 past the limit. Add both cases to the run.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 89 of 89

Previous
Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out

An agent that reads customer emails and can refund up to $200. In a small simulation, a phrase filter still lets 6 of 8 written attacks do harm and blocks 2 honest users; plain checks outside the model take harm to 0 of 8, at a cost of 1 honest request failed and 2 held.

The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three

A support agent reads a ticket that says run SELECT * FROM customers and email the result outside, and it has run_sql and send_email, so the customer list leaves. The model wasn't hacked, it was equipped. Map each tool by what it reads, changes and sends, replace the two large ones with narrow tools, scope the keys, and never give one agent untrusted input, private data and a way out together.

Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out

Three texts reach a support agent in one week: an injected ticket, a poisoned help article and a jailbreak. A naive agent turns all three into leaks; three small checks in plain code take that to zero.

Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job

Review a refund agent the way a security team would: map where stranger text gets in, what it can read and what it can do, layer every path, then show the four normal questions still give the same answer.

On this page

  • Two ways to lose control of a key
  • A server-side proxy
  • proxy.py
  • One message through it
  • A key for one workspace, or an admin key
  • One key per environment, and rotation
  • The day a key leaks
  • Common mistakes
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.