Diagramming Data Flows and Trust Boundaries
Work through a level-1 data-flow diagram for a cover-upload feature: choose the elements, keep the diagram as data, let a small script reject impossible flows, list every flow that crosses a trust boundary and export the picture for Graphviz.
Contentsand lesson path
On this page
- The problem
- Step 1: Choose the elements
- Step 2: Write the diagram as data
- Step 3: Check the diagram and list the crossings
- Step 4: Test the checker on a common mistake
- Step 5: Draw the picture
- Check your understanding
- Apply it
- Review prompt
Lessons of Threat Modeling
- Four Questions Behind Every Threat Model Concept · 15 min
- Diagramming Data Flows and Trust Boundaries Worked example · 25 min
- STRIDE per Element on a Sample Service Lab · 30 min
- Attack Trees for the Threats That Matter Worked example · 20 min
- From Threats to Owned, Verifiable Mitigations Worked example · 20 min
- Threat Modeling Check Knowledge check · 8 questions
What you will learn
- Draw a data-flow diagram that marks assets, entry points and trust boundaries at a level of detail suited to the decision being made.
01. The problem
BookSwap, the book-lending site from lesson 1, is adding cover photos. A member picks an image, the browser sends it to the web API, and the API stores it in a cloud storage bucket so it can be shown on the book page. Before the team writes code, the security champion asks one question: which parts of this feature handle data that crosses between different levels of trust? Those are the places that need controls, and the place to start looking for threats.
Your job in this worked example is to answer question 1 of the four questions, "what are we working on?", with a diagram detailed enough for that decision. You will finish with three things: a level-1 data-flow diagram kept as a JSON file, a list of assets and entry points, and the list of flows that cross a trust boundary.
You need Python 3.10 or later and nothing else. Make a folder called dfd-lab and work inside it. Graphviz is optional, for drawing the final picture.
02. Step 1: Choose the elements
A data-flow diagram (DFD) shows how data moves through a system. It uses only four kinds of element, plus one extra line for threat modelling:
- An external entity is a person or system you do not control, which sends data in or receives data out. The member's browser and the email provider are external entities. Draw them as rectangles.
- A process is code that you run and that transforms or moves data: the web API, the email worker. Draw them as circles or rounded boxes.
- A data store is a place where data rests: the Postgres database, the cover bucket, a log file. Draw them as cylinders or parallel lines.
- A data flow is an arrow showing data in motion between two elements, labelled with what it carries.
- A trust boundary is a dashed line wherever the level of trust or privilege changes, for example between the internet and your API, or between your network and a vendor's service.
DFDs come in levels. A context diagram (level 0) shows the whole system as one process with its external entities. A level-1 diagram opens that box to show the main processes and stores. For the upload decision, level 1 is right: you need to see the API, the bucket and the browser separately, but there is no value in drawing every module inside the API.
One rule catches many drawing mistakes: every data flow has a process at one end. Data does not move by itself. A browser cannot write into a database, and one database cannot copy itself into another, unless some code does the moving. If your diagram shows such a flow, a process is missing, and that missing process is often where the threats are.
03. Step 2: Write the diagram as data
Drawing tools are fine, but a diagram kept as text can be checked by a script and reviewed in a pull request. Each element gets a type and a zone. A zone is a group of elements that share one level of trust; a boundary exists wherever a flow goes from one zone to another. Here there are four zones: the internet (untrusted callers), the app zone (BookSwap's own services), the data zone (stores that need their own credentials to reach) and the vendor zone (the email provider's systems).
The file also lists assets: what each element holds that an attacker would want. Write it as dfd-lab/bookswap.json.
{
"system": "BookSwap level 1: cover uploads",
"elements": {
"member": {"type": "external", "zone": "internet", "label": "Member browser"},
"api": {"type": "process", "zone": "app", "label": "Web API"},
"worker": {"type": "process", "zone": "app", "label": "Email worker"},
"db": {"type": "store", "zone": "data", "label": "Postgres"},
"covers": {"type": "store", "zone": "data", "label": "Cover bucket"},
"mailer": {"type": "external", "zone": "vendor", "label": "Email provider"}
},
"flows": [
{"id": "F1", "from": "member", "to": "api", "data": "login, search, borrow"},
{"id": "F2", "from": "member", "to": "api", "data": "cover image upload"},
{"id": "F3", "from": "api", "to": "db", "data": "member and loan rows"},
{"id": "F4", "from": "api", "to": "covers", "data": "stored cover image"},
{"id": "F5", "from": "api", "to": "worker", "data": "welcome email job"},
{"id": "F6", "from": "worker", "to": "mailer", "data": "email + API key"}
],
"assets": {
"db": ["password hashes", "member emails", "loan history"],
"covers": ["uploaded images"],
"worker": ["email provider API key"]
}
}Notice that F1 and F2 both go from the browser to the API but are listed separately. They use the same connection, but they carry different data and reach different code, so they attract different threats. Splitting flows by purpose, not by network connection, keeps the next step precise. The two flows from the internet, F1 and F2, are BookSwap's entry points for this feature: the places where outside input reaches its code.
04. Step 3: Check the diagram and list the crossings
The script below does three things. It rejects flows that break the "process at one end" rule, it prints every flow whose two ends are in different zones, and it writes a Graphviz file with one dashed cluster per zone. Save it as dfd-lab/dfd.py.
"""Check a data-flow diagram kept as JSON and export it for Graphviz."""
import json
import sys
model = json.load(open(sys.argv[1]))
elements, flows = model["elements"], model["flows"]
problems = []
for f in flows:
ends = [elements.get(f["from"]), elements.get(f["to"])]
if None in ends:
problems.append(f"{f['id']}: unknown element in {f['from']} -> {f['to']}")
continue
if "process" not in (ends[0]["type"], ends[1]["type"]):
kinds = f"{ends[0]['type']} -> {ends[1]['type']}"
problems.append(f"{f['id']}: {kinds} has no process; data only moves "
"when code moves it")
for p in problems:
print("PROBLEM", p)
if problems:
sys.exit(1)
print(model["system"])
crossing = [f for f in flows
if elements[f["from"]]["zone"] != elements[f["to"]]["zone"]]
print("Flows that cross a trust boundary:")
for f in crossing:
a, b = elements[f["from"]]["zone"], elements[f["to"]]["zone"]
print(f" {f['id']} {f['from']:>6} -> {f['to']:<6} {a} -> {b}: {f['data']}")
inside = [f["id"] for f in flows if f not in crossing]
print(f"Flows inside one zone: {', '.join(inside) or 'none'}")
print("Assets and the flows that touch them:")
for owner, assets in model["assets"].items():
touching = [f["id"] for f in flows if owner in (f["from"], f["to"])]
print(f" {owner}: {', '.join(assets)} via {', '.join(touching)}")
shapes = {"external": "box", "process": "ellipse", "store": "cylinder"}
with open("bookswap.dot", "w") as out:
out.write("digraph dfd {\n rankdir=LR;\n")
for zone in sorted({e["zone"] for e in elements.values()}):
out.write(f' subgraph cluster_{zone} {{\n label="{zone}"; style=dashed;\n')
for key, e in elements.items():
if e["zone"] == zone:
shape = shapes[e["type"]]
out.write(f' {key} [label="{e["label"]}", shape={shape}];\n')
out.write(" }\n")
for f in flows:
out.write(f' {f["from"]} -> {f["to"]} [label="{f["id"]}: {f["data"]}"];\n')
out.write("}\n")
print("Wrote bookswap.dot")python3 dfd.py bookswap.jsonBookSwap level 1: cover uploads
Flows that cross a trust boundary:
F1 member -> api internet -> app: login, search, borrow
F2 member -> api internet -> app: cover image upload
F3 api -> db app -> data: member and loan rows
F4 api -> covers app -> data: stored cover image
F6 worker -> mailer app -> vendor: email + API key
Flows inside one zone: F5
Assets and the flows that touch them:
db: password hashes, member emails, loan history via F3
covers: uploaded images via F4
worker: email provider API key via F5, F6
Wrote bookswap.dotFive of the six flows cross a boundary, and each crossing is a question to ask later. F1 and F2 cross from the internet into the app zone, so the API must not trust anything they carry: file names, image sizes, the book id the cover is for. F3 and F4 cross into the data zone, so the API's database and bucket credentials matter, and so does what the API is allowed to do with them. F6 crosses into a vendor's system and carries an API key, so a leak of that flow is a leak of BookSwap's ability to send email.
F5 stays inside the app zone. It still matters, but it is not where trust changes, so it gets less attention in the first pass. If the worker ran under a different account or on a separate cluster, you would put it in its own zone, and F5 would become a crossing too. Where you draw boundaries is a design statement, so write down why.
The asset line shows why the data zone needs care: password hashes, email addresses and loan history are reached only through F3, so F3 is the flow to defend most carefully.
05. Step 4: Test the checker on a common mistake
A check you have never seen fail is a check you cannot trust. Make a copy of the model with one extra flow, the kind people draw when they hear "the browser uploads straight to the bucket", and run the script on it. Save this as dfd-lab/make-bad.py.
import json
model = json.load(open("bookswap.json"))
model["flows"].append(
{"id": "F7", "from": "member", "to": "covers", "data": "upload straight to bucket"})
json.dump(model, open("bad.json", "w"), indent=2)python3 make-bad.py
python3 dfd.py bad.json; echo "exit=$?"PROBLEM F7: external -> store has no process; data only moves when code moves it
exit=1The script stops with exit code 1, so it could fail a CI job. The finding is also a design lesson. Many real upload features do let the browser send files straight to storage, using a short-lived presigned URL that the API creates. Even then the flow is not "browser to store": it goes to the storage provider's upload service, which is a process run by someone else. The correct diagram adds that service as an external entity in the vendor zone, with a flow from the browser to it. That new arrow crosses a boundary your API never sees, which is exactly why presigned uploads need their own checks on size, content type and expiry.
06. Step 5: Draw the picture
Step 3 also wrote bookswap.dot, a text description of the drawing. Each zone becomes a dashed cluster, which is how trust boundaries usually look on a DFD. Look at the start of the file:
head -8 bookswap.dotdigraph dfd {
rankdir=LR;
subgraph cluster_app {
label="app"; style=dashed;
api [label="Web API", shape=ellipse];
worker [label="Email worker", shape=ellipse];
}
subgraph cluster_data {If Graphviz is installed (dot -V prints its version), dot -Tsvg bookswap.dot -o bookswap.svg draws the diagram; any online Graphviz viewer works too. The picture is for people. The JSON is the source of truth, because the script can check it and a reviewer can see each change in a diff.
07. Check your understanding
08. Apply it
For the skill project (a three-tier web application with a third-party payment integration), write the level-1 DFD as JSON in the same shape as bookswap.json:
- include the payment provider as an external entity, the payment redirect and the provider's webhook as separate flows, and an asset list;
- run
dfd.pyon it until it prints no problems, and keep the list of boundary crossings for lesson 3; - add one sentence at the top of the file saying which decision the diagram supports.
09. Review prompt
From memory, name the four DFD element types and the extra line threat modelling adds. State the rule that every data flow must follow, and explain in two sentences why a presigned upload URL changes the diagram. Then check yourself against steps 1 and 4.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.