Lesson 01 · 60 minutes
Write the use case and map the attack surface of an AI system
- Write the use case of an AI system and check with a script that no answer is empty and the success answer holds a number
- Name the five places where an AI system is attacked
- Write the asset map of a small AI system as a JSON file and find the assets that an untrusted party can write to
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your company, KR Books, will launch a support assistant for customers next month. The head of product asks you: "What can go wrong, and what do we need before launch?" You have a short description of the system and no test results. Before you can say what to defend, you must know what a system is for, so that you know what a failure is, and what it is made of. First you write the use case of the fraud model that KR Books also trains (lesson 2 attacks it). Then you map the assistant. Last, a second team asks you to do the same for their system.
The idea
An AI system is more than a model. It has five places where an attacker can push, and each place has its own kind of attack.
- Customer → Chat API: a question reaches the API (infrastructure)
- Attacker → Chat API: a stolen key opens the API (infrastructure)
- Attacker → Help documents: a review with a hidden instruction (data)
- Help documents → Prompt and retrieval: the review joins the prompt (application)
- Prompt and retrieval → Language model: the prompt goes to the hosted model (model)
- Language model → Order tool: the model calls a tool (agent and tools)
| Place | What lives there | An attack that enters here |
|---|---|---|
| Data | Training data, documents for retrieval, feedback, logs | A poisoned document or a flipped label |
| Model | Weights, the model file, a hosted model | A tampered model file, or theft of the weights |
| Application | The prompt, the retrieval step, the code that handles output | Prompt injection, or output that the page runs as code |
| Agent and tools | Functions that the model can call, their permissions, memory | A tool used for a purpose that nobody planned |
| Infrastructure | The API, servers, keys, libraries, logs | A stolen key or a library with a known flaw |
A map lists assets: things that have value, or that can be used against you. For each asset, ask the trust question: who can write to it? A person or a system that can change an asset can use it to attack. Sort every writer into one of three groups.
| Group | Meaning | Example |
|---|---|---|
| Trusted | You control it and you can hold it to account | Your developers |
| Untrusted | Anyone, or a large group that you do not control | Customers who post reviews |
| Third-party | A company that you depend on but do not control | A model provider |
Untrusted and third-party writers do not make an asset bad. They tell you where a control is needed.
Before you map, write down what a system is for: its use case. It says what "working" means, so it tells you what an attack costs. Write it as seven answers.
| Answer | What it says |
|---|---|
purpose | Why the system exists |
objective | The company goal that it serves |
owner | One named role that decides |
success | A number that you can check. Lesson 2 takes the floor of its test from it |
stop_when | A reason to switch the system off |
not_for | A decision that stays with people, or a task that a plain rule does better |
human | Where a person decides |
Worked example
1. Describe the system in words
You review the KR Books assistant, an invented system. Customers chat with it. It answers from help documents and from customer reviews, and it can look up the status of an order. A model hosted by a provider writes the answers. KR Books also trains a fraud model for its orders, and lesson 2 attacks it. Make the lab folder. mkdir -p makes a directory and the directories above it, and cd moves you into it.
mkdir -p ~/krlab/ai-security-fundamentals/kr-books
cd ~/krlab/ai-security-fundamentals/kr-books2. Write the use case of the fraud model
JSON is a plain-text format for structured data: {...} holds named values, and [...] holds a list. Create use-case.json. The numbers are examples. The recall of a class of case is the share of the real cases of that class that the model finds, and a trusted test set is data with known-good labels that nobody who trains the model can change. Lesson 2 measures them. The command cat > use-case.json <<'EOF' is a heredoc: it writes every line up to the line EOF into the file use-case.json.
cat > use-case.json <<'EOF'
{
"purpose": "Flag orders that look like fraud so that an analyst reviews them before dispatch",
"objective": "Keep fraud losses below 0.5 percent of sales",
"owner": "head of payments",
"success": "Every class of case has a recall of at least 0.80 on the trusted test set, every week",
"stop_when": "A weekly gate fails, or analysts overturn over 30 percent of flags in a week",
"not_for": "Closing an account or refusing a refund: a person decides those",
"human": "An analyst approves every block and checks 20 closed cases a week against the outcome"
}
EOFCreate check_usecase.py. It fails an empty answer, and a success measure without a number, because such a measure cannot fail. Four Python ideas are new:
- Input:
json.loadreads a JSON file into Python lists and dictionaries.sys.argvis the list of words on the command line, sosys.argv[1]is the first word after the script name. - Text:
record.get(name, "")gives the value of a key, or an empty text when the key is missing..strip()removes spaces at both ends of a text, and.rstrip()removes them at the end only. An f-string (a string that starts withf) puts the value of each{name}into the text, and{name:<10}pads it to 10 characters. - Tests:
A if test else BgivesAwhen the test is true, elseB.any(...)is true when at least one item fits, andc.isdigit()is true for a digit. - Result:
bad += bool(problem)adds 1 tobadwhenproblemis not empty.sys.exit(1)ends the script with exit code 1, which means failure.
kr-books/check_usecase.py
import json
import sys
FIELDS = ["purpose", "objective", "owner", "success", "stop_when", "not_for", "human"]
record = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "use-case.json"))
bad = 0
for name in FIELDS:
text = record.get(name, "").strip()
problem = ""
if not text:
problem = "EMPTY"
elif name == "success" and not any(c.isdigit() for c in text):
problem = "NO NUMBER"
bad += bool(problem)
print(f"{'FAIL' if problem else 'ok '} {name:<10} {problem}".rstrip())
print(f"use case: {len(FIELDS) - bad} of {len(FIELDS)} fields ok")
sys.exit(1 if bad else 0)python3 check_usecase.pyok purpose
ok objective
ok owner
ok success
ok stop_when
ok not_for
ok human
use case: 7 of 7 fields okThe checker finds an empty answer and a success measure with no number. It cannot tell you whether the number is a good one.
3. Write the asset map
Create assets.json. The actors object says how far you trust each writer. Each asset has an id, a name, one of the five layers and the list of its writers.
kr-books/assets.json
{
"system": "KR Books assistant",
"actors": {
"customer": "untrusted",
"staff": "trusted",
"developer": "trusted",
"orders-service": "trusted",
"model-provider": "third-party"
},
"assets": [
{"id": "A1", "name": "help documents: FAQ, book pages, customer reviews", "layer": "data", "writers": ["staff", "customer"]},
{"id": "A2", "name": "language model, hosted by a provider", "layer": "model", "writers": ["model-provider"]},
{"id": "A3", "name": "retrieval step and system prompt", "layer": "application", "writers": ["developer"]},
{"id": "A4", "name": "order-status tool", "layer": "agent", "writers": ["developer"]},
{"id": "A5", "name": "chat API and its server", "layer": "infrastructure", "writers": ["developer"]},
{"id": "A6", "name": "orders database, with delivery notes", "layer": "data", "writers": ["orders-service", "customer"]}
]
}Look at A6. The orders service writes orders, but customers type the delivery notes. Both are writers.
4. Write the script that asks the trust question
Create assets.py. It prints each asset with its writers, marks an asset ASK when any writer is not trusted, and checks that every layer has an asset. Some Python parts are new here; the rest is as in step 2 ({name:<15} pads to 15 characters). [x for x in xs if test] builds a new list from the items that pass the test; the same shape inside {...} builds a set. a or b gives b when a is empty.
kr-books/assets.py
import json
import sys
LAYERS = ["data", "model", "application", "agent", "infrastructure"]
with open(sys.argv[1] if len(sys.argv) > 1 else "assets.json") as f:
system = json.load(f)
actors = system["actors"]
print(system["system"])
flagged = []
for asset in system["assets"]:
writers = ", ".join(f"{w} ({actors[w]})" for w in asset["writers"])
risky = [w for w in asset["writers"] if actors[w] != "trusted"]
mark = "ASK" if risky else "ok "
print(f'{mark} {asset["id"]} {asset["layer"]:<15} {asset["name"]}')
print(f" writers: {writers}")
if risky:
flagged.append(asset["id"])
print()
print("assets that untrusted or third-party writers can change:", flagged)
covered = {a["layer"] for a in system["assets"]}
print("layers with no asset:", [l for l in LAYERS if l not in covered] or "none")5. Run it
python3 runs a Python file. The script reads assets.json, or the file that you name after it.
python3 assets.pyKR Books assistant
ASK A1 data help documents: FAQ, book pages, customer reviews
writers: staff (trusted), customer (untrusted)
ASK A2 model language model, hosted by a provider
writers: model-provider (third-party)
ok A3 application retrieval step and system prompt
writers: developer (trusted)
ok A4 agent order-status tool
writers: developer (trusted)
ok A5 infrastructure chat API and its server
writers: developer (trusted)
ASK A6 data orders database, with delivery notes
writers: orders-service (trusted), customer (untrusted)
assets that untrusted or third-party writers can change: ['A1', 'A2', 'A6']
layers with no asset: noneHalf of the assets take input from someone you do not control. These three are where the rest of the course looks first. The model (A2) is a dependency. The documents (A1) and the delivery notes (A6) are text that customers wrote, and the assistant will read that text.
6. Test the layer check
Make a copy of the map without the API and run the script on it. grep -v keeps the lines that do not match. tail -2 shows the last two lines. rm deletes the test file.
grep -v '"A5"' assets.json > assets-test.json
python3 assets.py assets-test.json | tail -2
rm assets-test.jsonassets that untrusted or third-party writers can change: ['A1', 'A2', 'A6']
layers with no asset: ['infrastructure']A map with a layer missing is not finished. Lessons 4, 9 and 10 read assets.json, and lessons 6 and 8 use its ids.
Your turn
The clinic team of your company wants the same map for the KR Clinic booking assistant. Save the fact sheet as clinic-facts.txt in a new folder, ~/krlab/ai-security-fundamentals/clinic.
clinic/clinic-facts.txt
KR Clinic booking assistant (an invented system)
Patients chat with the assistant on the clinic website. It books, moves and
cancels appointments, and it answers questions about opening hours and how
to prepare for a visit.
Part What it is Who writes it
C1 Help pages and preparation leaflets that it reads Clinic staff
C2 Doctor profiles, imported each night from a partner The partner hospital
C3 Booking database; a patient types a "reason for visit" The booking system and the patient
C4 The language model, run by a cloud provider The model provider
C5 The prompt and the retrieval code The developers
C6 The booking tool: find a slot, book, cancel The developers
C7 The chat API and the web server The developersWrite assets.json for the clinic in that folder, with one asset for each part C1 to C7. Decide the layer of each part and the trust group of each writer: staff and developers are employees, the partner and the provider are other companies, and patients are the public. Run assets.py on your file. The script stays in kr-books: from the clinic folder, run python3 ../kr-books/assets.py.
Lessons 4 and 9 read this file. If you lost yours, the lab files of the course hold one. Open it only after your own try.
The finished file: assets.json of the clinic
clinic/assets.json
{
"system": "KR Clinic booking assistant",
"actors": {
"patient": "untrusted",
"staff": "trusted",
"developer": "trusted",
"booking-system": "trusted",
"partner": "third-party",
"model-provider": "third-party"
},
"assets": [
{"id": "C1", "name": "help pages and preparation leaflets", "layer": "data", "writers": ["staff"]},
{"id": "C2", "name": "doctor profiles, imported each night", "layer": "data", "writers": ["partner"]},
{"id": "C3", "name": "booking database, with the reason for visit", "layer": "data", "writers": ["booking-system", "patient"]},
{"id": "C4", "name": "language model, run by a cloud provider", "layer": "model", "writers": ["model-provider"]},
{"id": "C5", "name": "prompt and retrieval code", "layer": "application", "writers": ["developer"]},
{"id": "C6", "name": "booking tool", "layer": "agent", "writers": ["developer"]},
{"id": "C7", "name": "chat API and web server", "layer": "infrastructure", "writers": ["developer"]}
]
}Check yourself
The team says: "We only use a hosted model, so there is nothing for us to attack." What do you answer?
The model is one asset. The team still owns the data that goes into the prompt, the retrieval step, the tools, the API and the keys. Each one has writers, and some writers are untrusted.
Why is a customer a writer of the orders database if customers cannot open it?
A writer is anyone whose content ends up in the asset, even by an indirect route. A customer types a delivery note, the orders service saves it, and the assistant later reads it. The note is the customer's text inside your data.
An asset has only trusted writers. Does it need no control?
It still needs controls against other threats, such as theft or a mistake by a trusted person. The trust question finds the places where input is a risk. It does not prove that a place is safe.
Where in the five places does a stolen API key belong, and why?
In infrastructure. The key is a credential of the system, not a part of the model or of the data. The attacker uses it to reach every other place.
A model has an accuracy of 0.95 but finds only 4 in 10 of the cases of one class. Does it meet the success answer of the fraud use case?
No. The answer asks for a recall of at least 0.80 for every class, and one class has 0.40. A high average can hide a failing class.
Field notes
- Add two more columns when the map grows: the owner (a named person) and the data class (public, internal, personal, secret).
- Models, prompts, embeddings and evaluation sets are assets and need version control like code. Record the model name and its digest, and note whether you can pin a hosted version.
- Count the less obvious assets: chat logs (they hold personal data), the vector index, a system prompt that carries a secret, and the credentials of every tool.
- The five places match the way the standards sort attacks: the OWASP Top 10 for LLM Applications mostly names risks in the application and agent layers, and NIST AI 100-2 groups attacks by where in the life of a model they act.