Lesson 24 of 28Quality and safety
Threat Modeling and Security by Design
Find security flaws while they are still lines on a whiteboard: data flow diagrams, trust boundaries, STRIDE, and the controls that design them out.
Your team is about to build file uploads: users attach PDFs and images to their projects, a worker makes thumbnails, and the files live in S3. The ticket says "add upload endpoint". Nobody has asked who can read another tenant's files if they guess the key, what happens when someone uploads a 40 GB file or an SVG with a script in it, or what the thumbnail worker can reach if a malicious image takes it over. Those questions are cheap to answer on a whiteboard and very expensive to answer in an incident report. Threat modeling is the habit of asking them on purpose, before the code exists, in a way a whole team can repeat.
The four questions
Adam Shostack's framing, now the basis of the Threat Modeling Manifesto, reduces the practice to four questions:
- What are we working on? A diagram of the system or feature, at the level of detail where security decisions live.
- What can go wrong? A structured brainstorm of threats, so you do not only find the ones you already worry about.
- What are we going to do about it? For each threat: mitigate, eliminate (remove the feature or data), transfer (to a provider or insurer), or accept, with a named owner.
- Did we do a good job? Check the model against the built system, and check whether the mitigations actually shipped.
Notice what is missing: attacker personas, exploit code, a security team. Threat modeling is a design activity. The engineers who know how the system works are the right people to do it, and the output is a list of tickets, not a report.
Draw the system: data flows and trust boundaries
The standard picture is a data flow diagram (DFD) with only five kinds of thing:
- External entities: people or systems you do not control (a browser user, a payment provider).
- Processes: code you run (the API, a worker).
- Data stores: where data rests (Postgres, S3, a cache, log files).
- Data flows: arrows showing data moving, labelled with what moves and how.
- Trust boundaries: lines where the level of trust changes. Every place where data crosses from something you control less into something you control more.
Trust boundaries are the most important part. Almost every real vulnerability sits on a boundary: input that was trusted because it came from "our" frontend, a token that was not checked because the call was "internal", a file that was processed because it was "just an image".
The browser is an external entity. Anything it sends is attacker-controlled, including headers, file names, sizes and content types.
Draw at the level of the feature, not the company. A whiteboard photo is fine. The value is in the conversation the drawing forces: someone always says "wait, the worker has write access to the whole bucket?"
What can go wrong: STRIDE per element
STRIDE (from Microsoft, 1999) is a checklist of six threat categories, each the opposite of a security property:
| Threat | Violates | Example in the upload feature | Typical mitigation |
|---|---|---|---|
| Spoofing | Authentication | A stolen session cookie used to upload as someone else | Strong authn, short sessions, HttpOnly and SameSite cookies |
| Tampering | Integrity | Changing the object key in a presigned request to overwrite another file | Signatures that cover the key, server-chosen keys |
| Repudiation | Non-repudiation | "I never deleted that file", and you have no record | Append-only audit log with actor, action, time |
| Information disclosure | Confidentiality | Guessable keys like /uploads/123.pdf in a public bucket | Private bucket, random keys, short-lived signed reads |
| Denial of service | Availability | A 40 GB upload, or a "zip bomb" image that eats the worker's memory | Size limits in the signature, worker memory and time limits |
| Elevation of privilege | Authorisation | A crafted image gets code execution in the worker, which has broad IAM rights | Sandboxed worker, least-privilege IAM role |
The trick that makes STRIDE practical is applying it per element. Not every category applies to every kind of DFD element. External entities can be spoofed and can repudiate, but you cannot "tamper with" a user. A data flow can be tampered with, read, or blocked, but it cannot be "elevated". The standard mapping cuts the brainstorm to the threats that make sense:
Press Run (⌘ Enter) to see what happens.Thirty-one prompts for one small feature sounds like a lot, but most take seconds: "Tampering on the browser-to-API flow? TLS, and we validate the body. Next." The few that make the room go quiet are the ones you came for. (Repudiation on a data store mostly matters when the store is a log.)
Match each finding to its STRIDE category.
What we do about it: the upload feature, worked
Here is what a 45-minute session on that diagram typically produces. Each line becomes a ticket.
- Server chooses the key. The API generates
tenants/{tenant_id}/{uuid4}and signs a URL for exactly that key. The client never names the path, so it cannot overwrite or guess other files. - Limits live in the signature. Use a presigned POST with a
content-length-rangecondition and a fixedContent-Type, and a short expiry (minutes). The upload never touches your code, so this is the only place limits can be enforced. - Never serve uploads from your app's origin. An uploaded SVG or HTML file served from
app.example.comruns script with your users' cookies. Serve downloads from a separate domain, withContent-Disposition: attachmentandX-Content-Type-Options: nosniff. - Treat the worker as hostile territory. Run it in its own container with memory and CPU limits, no network egress except the bucket, and an IAM role that can read
incoming/and writethumbnails/only. - Check the real type. Sniff magic bytes, not the extension or the client's content type. Re-encode images, which strips metadata such as GPS location as a bonus.
- Audit. Write who uploaded, downloaded and deleted what, to an append-only log.
Prioritising
You will find more threats than you can fix this sprint. Rank them by likelihood times impact on a simple three-point scale (low, medium, high), and be explicit about what you accept. "Accepted: an authenticated user can upload many small files; mitigated later by per-tenant quotas" is a valid outcome, as long as it is written down with an owner.
You may meet DREAD (damage, reproducibility, exploitability, affected users, discoverability), which scores each threat 1 to 10 on five axes. Microsoft itself stopped using it. Scores swing wildly between people, discoverability rewards obscurity, and the false precision of "7.4" hides the fact that it was a guess. For known vulnerability classes, CVSS gives a standard severity, but for design-time threats a short, argued ranking beats a number.
Two other tools are worth knowing by name. An attack tree puts the attacker's goal at the root ("read another tenant's file") and breaks it into alternative paths ("guess a key", "replay a signed URL", "abuse a support tool"), which shows where one control blocks many paths. LINDDUN does for privacy what STRIDE does for security: Linking, Identifying, Non-repudiation, Detecting, Data disclosure, Unawareness and unintervenability, and Non-compliance. Use it when the feature handles personal data, because a system can be perfectly secure and still track people in ways they never agreed to.
Design principles that prevent whole classes of bugs
Most of these come from Saltzer and Schroeder's 1975 paper and have aged remarkably well.
- Least privilege. Every process, role and token gets only what its job needs. The thumbnail worker cannot delete files, so a compromised worker cannot either.
- Defence in depth. Assume each control will fail once. Authz in the API and row-level security in the database and a private bucket.
- Secure defaults. New buckets private, new endpoints authenticated, new roles empty. Insecure must be the thing you opt into.
- Fail closed. If the policy service is down, deny. If a token cannot be parsed, deny. An
except: return Truein an authz check is a breach waiting for an outage. - Complete mediation. Check authorisation on every access, not once at login. Caching "user may see project 7" for an hour means revoking access takes an hour.
- Minimise attack surface. Every endpoint, port, admin panel and dependency is something to defend. Delete what you do not use.
- Separation of duties. No single person or key can do the dangerous thing alone: deploys need review, refunds over a limit need a second approver.
try: ... except Exception: return True "so an outage does not lock users out". Which principle does this break, and what is the fix?Architectural controls
Some threats are best handled by the shape of the system rather than by one more if.
Centralise authorisation. When every route writes its own ownership check, one forgotten check is a broken object level authorisation bug (the top OWASP API risk, covered in API Security). Put decisions behind one function or service and call it everywhere. Policy as code tools make the rules reviewable and testable: OPA with its Rego language, Cedar (an open-source policy language from AWS), or OpenFGA for relationship-based rules in the style of Google's Zanzibar ("can user X view document Y because they are in a team that owns its folder").
Isolate tenants in the database. In multi-tenant SaaS, the nightmare is one customer seeing another's data because a query forgot WHERE tenant_id = .... Postgres row-level security makes the database add that filter itself:
ALTER TABLE files ENABLE ROW LEVEL SECURITY;
ALTER TABLE files FORCE ROW LEVEL SECURITY; -- apply to the table owner too
CREATE POLICY tenant_isolation ON files
USING (tenant_id = current_setting('app.tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);The app sets the tenant per transaction with SET LOCAL app.tenant_id = '...' (or set_config(..., true)), which is also safe behind a transaction-mode connection pooler. Two details seniors know: table owners bypass RLS unless you FORCE it, and superusers and roles with BYPASSRLS always bypass it, so the app must not connect as either.
Keep secrets out of code and images. Use a secrets manager (AWS Secrets Manager, GCP Secret Manager, Vault), short-lived credentials from workload identity instead of long-lived keys, and rotation you have actually tested.
Make outbound requests safe. Any feature that fetches a URL a user supplied ("import from link", webhooks, link previews) is a server-side request forgery (SSRF) risk: the attacker points it at http://169.254.169.254/ (the cloud metadata service, which can hand out credentials) or at internal admin services. Validate the resolved IP address, allow-list public addresses rather than block-listing private ones, connect to the IP you checked (so DNS cannot change between the check and the request), disable redirects or re-check each hop, and on AWS require IMDSv2. The strongest version is architectural: route all user-driven fetches through one egress proxy that enforces the rules.
Press Run (⌘ Enter) to see what happens.What does this print?
import ipaddress def blocklist_ok(ip): return not ipaddress.ip_address(ip).is_private def allowlist_ok(ip): return ipaddress.ip_address(ip).is_global # 100.64.0.0/10 is carrier-grade NAT space, often used inside cloud networks ip = "100.64.0.1" print(blocklist_ok(ip), allowlist_ok(ip))
Modern threat sources
Two areas now produce a large share of real incidents and belong in every model.
The supply chain. Your dependencies, build tools and CI runners execute code with your secrets. Typosquatted packages, hijacked maintainer accounts, the 2024 xz backdoor and compromised GitHub Actions have all shipped malicious code into builds that passed every test. Treat CI as a trust boundary in your DFD: commit lockfiles, pin third-party actions to a full commit SHA, give CI jobs the narrowest token and cloud role, generate an SBOM, and prefer packages published with provenance (Sigstore, npm and PyPI trusted publishing).
LLM features. A model that reads a support ticket, a web page or a PDF can be steered by instructions hidden in that content (prompt injection). In DFD terms, the model's output is untrusted input, and any tool it can call is a privileged process sitting right next to a boundary. AI Security covers the defences: least-privilege tools, human approval for destructive actions, and validating everything the model produces.
Running it on a team
The model that gets done beats the perfect one that does not. A format that works:
Order a 45-minute threat modeling session for a new feature.
- Tap the steps below in the right order.
Invite the people who build it, someone who will operate it, and, if you have one, a security engineer as a guide rather than an approver. Store the diagram and threat list next to the design doc or in the repo, and update them when the design changes: a model of last year's system is worse than none because it gives false confidence. OWASP Threat Dragon and the Microsoft Threat Modeling Tool both draw DFDs and suggest STRIDE threats per element. Code-based tools such as pytm keep the model in version control. A whiteboard and a ticket tracker are enough to start.
- threat model
- A structured answer to what we are building, what can go wrong, what we will do about it, and whether we did a good job.
- trust boundary
- A line in a system where data passes between parts with different levels of trust, and where checks must happen.
- STRIDE
- Spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege: six threat categories.
- STRIDE per element
- Applying only the STRIDE categories that fit each kind of diagram element: external entity, process, store or flow.
- row-level security
- A database feature that filters every query on a table by a policy, such as the current tenant.
- SSRF
- Server-side request forgery: tricking a server into making requests to internal or cloud metadata addresses on the attacker's behalf.
- LINDDUN
- A privacy threat framework: linking, identifying, non-repudiation, detecting, data disclosure, unawareness, non-compliance.