AI Application Security
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Security for an AI feature is mostly ordinary application security with one strange addition: the part of your system that follows instructions can be given instructions by anyone who can get text in front of it. Everything else, keys, authentication, least privilege, logging, still applies, and it's still where most real damage happens. This lesson draws a simple threat model for the support service, then goes through the controls in the code.
What you'll learn
- A small threat model: what you protect, who can reach it and what they can try.
- Keeping keys and tokens out of places they leak.
- Authentication, budgets and limits at your API's edge.
- Handling model output as untrusted too.
- A preflight scan that blocks a deploy with a secret in it.
Before you start
A small threat model
Write these three lists before you write code:
| Protect | Who can reach it | What they might try |
| Your API key and spend | Anyone who finds the key, or can call your endpoint | Steal the key; run up your bill through your own API |
| Customer data in prompts and logs | Staff, log readers, the model's other users of the same text | Read logs; get the model to repeat another customer's data |
| Your instructions (system prompt) | Any customer who can chat | Ask the model to reveal them |
| Actions the system can take | Whoever controls text the model reads | Inject instructions to trigger actions |
| The reputation of your replies | Anyone who can steer the model | Make it say something harmful or promise something |
Treat your system prompt as something that will eventually be seen. Don't put secrets or private logic in it. Whether a customer can extract it is a weak control, so the useful questions are "what would it cost us if they did?" and "is anything in there that shouldn't be?".
Keys and tokens
- Server-side only. Calls to the API come from your back end. The documentation notes that organizations with certain retention settings can't call the API from a browser at all (a 401 mentioning CORS), and the fix is the same either way: send requests from your own server.
- Environment, not source. The key comes from
ANTHROPIC_API_KEY. Our Settings object prints as api_key=*** and our log formatter replaces fields named api_key, token, authorization and similar with ***, which the tests check.
- Separate keys per environment. A development key in production, or the reverse, makes spend and incidents hard to untangle. The Console also lets you create workspaces with their own limits.
- Be ready to rotate. If a key leaks, you revoke it and deploy another. That only works quickly if the key is configuration, not code.
Your API's front door
Your endpoint is a door to a metered resource. In the service:
- Every route except
/healthz and /readyz needs a bearer token, compared with hmac.compare_digest so timing doesn't reveal how many characters matched. The tests check that missing, wrong and absent tokens all give 401.
- Interactive docs are turned off (
/docs returns 404). A production service shouldn't advertise its schema to strangers.
- The request body is validated before any model call: a user id of letters, digits, dot, dash and underscore; an order id shaped like
A100; bounded text length.
- Budgets are checked before the call, so a looping client can't spend more than its allowance (lesson 8.10).
A single shared token like ours suits an internal service. If your own users call the API directly, use real per-user authentication and make the user id come from the verified identity, not from the request body. In our service the body's user_id is only a trusted-caller convenience.
Model output is untrusted too
The model's reply can contain whatever an attacker managed to persuade it to write. So:
- Never execute it, never build SQL, shell commands or file paths from it.
- Escape it when you show it in a web page. If you render Markdown, remember that links and images can point at an attacker's server and carry data in the URL.
- Check it against rules your code knows (lesson 8.5). Our service rejects drafts that promise refunds, mention orders nobody looked up or contain something shaped like a key.
- Keep a person in front of anything with consequences.
Least privilege, again
The strongest defence against injection is that a successful injection can't do much. The service's model has no tools at all. It sees only the one order record for this request. It can't send email or move money. If you do add tools (Modules 4, 6 and 7), apply everything from those lessons: narrow tools, approvals for writes, per-agent tool sets.
Block deploys that contain secrets
Most leaked keys are committed by accident. A preflight script scans the project for key-shaped strings and fails the pipeline. It also checks that .gitignore lists .env, and that an evaluation report exists with its security cases passing (lesson 8.6):
"""Run before every deploy: python preflight.py . evals/last_report.json
Exits non-zero if something is wrong, so a pipeline stops."""
import json
import re
import sys
from pathlib import Path
SECRET_PATTERNS = {
"Anthropic-style API key": re.compile(r"sk-ant-[A-Za-z0-9_-]{20,}"),
"generic sk- key": re.compile(r"\bsk-[A-Za-z0-9]{32,}\b"),
"private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
"bearer token literal": re.compile(r"Bearer\s+[A-Za-z0-9._-]{30,}"),
}
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__"}
def scan_secrets(root: Path) -> list[str]:
hits = []
for path in root.rglob("*"):
if not path.is_file() or SKIP_DIRS & set(path.parts) or path.suffix in {".png", ".jpg", ".gz", ".zip"} or path.stat().st_size > 1_000_000:
continue
try:
text = path.read_text(errors="ignore")
except OSError:
continue
for name, pattern in SECRET_PATTERNS.items():
if pattern.search(text):
hits.append(f"{path.relative_to(root)}: looks like a {name}")
return hits
def check(root: Path, report_path: Path | None, min_pass_rate: float = 0.9) -> list[str]:
problems = scan_secrets(root)
gitignore = root / ".gitignore"
if not gitignore.exists() or not re.search(r"^\.env\s*$", gitignore.read_text(), re.M):
problems.append(".gitignore must list .env")
if (root / ".env").exists() and not gitignore.exists():
problems.append(".env exists but there is no .gitignore")
if report_path is None or not report_path.exists():
problems.append("no evaluation report found; run the evals first")
else:
results = json.loads(report_path.read_text())
rate = sum(r["passed"] for r in results) / len(results) if results else 0.0
if rate < min_pass_rate:
problems.append(f"evaluation pass rate {rate:.0%} is below {min_pass_rate:.0%}")
security = [r for r in results if "security" in r.get("tags", [])]
if not security:
problems.append("the evaluation set has no security cases")
elif not all(r["passed"] for r in security):
problems.append("a security case is failing")
return problems
if __name__ == "__main__":
root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
report = Path(sys.argv[2]) if len(sys.argv) > 2 else None
found = check(root, report)
for p in found:
print("FAIL:", p)
print("preflight passed" if not found else f"{len(found)} problem(s)")
sys.exit(1 if found else 0)
It's a seatbelt, not a guarantee. It finds the common shapes, and a dedicated secret-scanning tool in your repository host is better. We tested it with a fake key-shaped string, a missing .gitignore, a failing security case, a report with no security cases and a missing report. All were caught, and a clean project passed.
Abuse and policy
Using Claude in a public product means your users' behaviour is partly your responsibility. Anthropic's guidance for jailbreak mitigation suggests responding to repeat offenders, for example by throttling or banning users who repeatedly trigger the same kind of refusal. The simplest hook is the metrics the service already keeps: count flagged messages per user and look at the top of that list. Also read Anthropic's usage policy and terms for your use case; this course doesn't replace them or legal advice.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A developer pushes a quick fix and an .env file with a real key ends up in the repository. The preflight step in CI finds sk-ant- followed by a long string and fails the build, so the key never reaches the main branch. Because the key is read from the environment, rotating it takes five minutes: create a new key, update the secret store, redeploy. Without that habit, the same mistake means searching the code and history for every place it was pasted.
Mistakes to avoid
- Calling the API from the browser or a mobile app with an embedded key.
- Logging full prompts and replies "for debugging" and then keeping them forever.
- Putting secrets or business rules into the system prompt.
- Believing a prompt that says "never reveal this" is a security control.
- Skipping authentication on an internal endpoint because "nobody knows the URL".
Security notes
This whole lesson is security notes, so one more point: assume every layer will sometimes fail, and ask what the next layer does. Authentication stops outsiders. Validation stops malformed input. Screening and data framing reduce injection. Output checks catch bad drafts. A person stops consequences. Budgets stop runaway cost. Logs let you find out afterwards.
Cost and speed
Security controls here are cheap. The one that costs money is screening with a model; use it where the stakes justify a small extra request, and note that the documentation points at a lightweight model for it.
Key takeaways
- Start with a three-column threat model: what you protect, who reaches it, what they try.
- Keys live in the server's environment and never appear in logs, repr output or the repository.
- Authenticate and validate before spending a single token.
- Treat model output as untrusted; escape it, check it, and never execute it.
- Least privilege and a person in the loop limit what a successful attack can do.
Lesson recap: protect keys, authenticate first, distrust output, and shrink the blast radius.
Quick quiz
- Why should API calls come from your server and not the browser?
- Why compare tokens with
hmac.compare_digest?
- Name two ways model output can be dangerous.
- What does the preflight script check?
- Is "never reveal these instructions" a security control?
Answers and explanations
- A key placed in a browser or app can be read by anyone. The server keeps it secret and is the right place to enforce authentication and budgets.
- It takes the same time however many characters match, so timing can't be used to guess a token.
- For example, it may be executed or used to build commands or queries, or rendered as HTML or Markdown with a link that carries data to an attacker.
- Secret-shaped strings in the project, that
.gitignore lists .env, and that an evaluation report exists with passing security cases and an overall pass rate above the threshold.
- No. It's a weak request the model usually follows, not an enforced boundary. Assume the prompt can be extracted and keep secrets out of it.
Official references and further reading
Related tutorials