Skip to content
Derar Sattouf

Threat Modeling for Developers: A 60-Minute STRIDE Workflow

Updated Security

Threat Modeling for Developers: A 60-Minute STRIDE Workflow

Most security bugs that scanners cannot find are design bugs. The upload endpoint that trusts file extensions, the admin API that shares a database user with the public API, the AI assistant that can read every customer's documents because "it just uses the search tool". No static analyzer flags these, because the code does exactly what it was designed to do. The design was the problem.

Threat modeling is how you find those problems while they are still cheap: on a whiteboard, before the code exists, or at least before the next big change ships. It sounds like a heavyweight ritual run by security specialists. It does not have to be. A developer team can run a useful session in an hour with a diagram, a table, and a handful of questions.

Everything is defensive: the goal is to understand how a system can fail so you can design the controls, not to produce attack recipes.

It complements OWASP Top 10 for Developers, which shows the code-level fixes for many threats you will find here, and Prompt Injection Defense for AI Agents and Secrets Management in 2026, which go deep on two recurring mitigations.

Threat modeling is structured thinking about what can go wrong in a system, what you'll do about it, and whether you did a good job. It's design review with an attacker's eyes. The Threat Modeling Manifesto frames it as four questions: What are we working on? What can go wrong? What are we going to do about it? Did we do a good enough job?

The 60-minute recipe: 10 minutes for scope and diagram, 10 for trust boundaries and assets, 25 for STRIDE per element, 10 to rate and decide, and 5 to write backlog items. Draw the diagram first. Without a data-flow diagram with trust boundaries, sessions turn into vague brainstorming. STRIDE is a mnemonic for six threat types: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege. Apply it to each element and each data flow crossing a trust boundary.

Rate simply: likelihood times impact on a three-level scale, or a plain High/Medium/Low. Precision is fake; consistency is valuable. Every threat needs a decision: mitigate, eliminate, transfer, or accept (with a named owner), and mitigations become backlog items with acceptance tests.

Keep the model alive. Store it in the repository next to the code (a Markdown file or threat-modeling-as-code), review it when the architecture changes, and link findings to issues. For privacy, use LINDDUN. For AI and agents, add threats such as prompt injection, tool abuse, data exfiltration through tool output, and excessive agency. A mediocre model that is done and acted on beats a perfect one that is never finished.

Why and when to threat model

Why

  • Cost curve. A design flaw found in a whiteboard session costs a conversation. The same flaw found in production costs a migration, an incident, and a disclosure.
  • Scanners find implementation bugs; models find missing controls. Missing rate limiting, missing tenant isolation, missing audit logging, missing approval step: these have no vulnerable line of code to point to.
  • Shared understanding. Drawing the system forces the team to agree on what it actually is. Many findings are really "we did not know that service could call that one".
  • Prioritization. Instead of fixing whatever the scanner reports, you spend effort where an attacker would profit.
  • Compliance evidence. Secure development frameworks and standards (for example NIST SSDF, ISO 27001 controls, SOC 2 change management, PCI DSS) expect risk analysis of design changes. A short written model is evidence.

When

TriggerDepth
New product or major architectureFull model (60 to 120 minutes), repeated per major component
New feature touching authentication, authorization, payments, personal data, file handling, or external integrationsFocused model (30 to 60 minutes)
New third-party integration or a new cloud serviceQuick model (15 to 30 minutes): trust boundary, credentials, data shared
Incident or near missRetrospective model of the affected flow
Adding an AI assistant, agent or tool serverDedicated model (see the section on AI and agent systems)
Small bug fix or UI tweakNone. Use a checklist

A good rule: if a change adds or alters a trust boundary, an entry point, a data store of sensitive data, or an actor, model it. If it does not, skip it.

Who

The people who know the system: the developers building it, an architect, someone from operations or SRE, and a product owner who knows the data and business rules. A security engineer helps but is not required; they bring the attacker mindset, and developers bring the system knowledge. Four to six people is the sweet spot. Rotate a moderator who keeps time and makes sure every threat ends in a decision.

The four-question framework

The Threat Modeling Manifesto and Adam Shostack's work structure the activity into four questions. Everything else here is machinery for answering them.

#QuestionActivityOutput
1What are we working on?Draw a data-flow diagram; list assets, actors, entry points, trust boundariesA diagram everyone agrees on
2What can go wrong?STRIDE per element; attack trees; abuse casesA list of threats
3What are we going to do about it?Choose mitigation, elimination, transfer, or acceptance; map to controlsDecisions, backlog items
4Did we do a good enough job?Review coverage; validate mitigations with tests; revisit after changesVerified controls, follow-up date

Question 4 is the one teams skip. Without it, a threat model is a document, not a feedback loop. Build verification into the output: each mitigation has a test, a configuration check, or a monitoring alert that proves it exists and stays in place.

Key vocabulary

TermMeaning
AssetSomething worth protecting: customer data, credentials, money, availability, reputation
ActorA person or system that interacts with the system: customer, admin, attacker, third-party service
Entry pointWhere data or control enters: API route, upload form, webhook, queue, admin console, CLI
Trust boundaryA line where the level of trust changes: internet to your edge, app to database, your cloud account to a SaaS vendor
ThreatA potential event that harms an asset
VulnerabilityA weakness that makes a threat possible
Control or mitigationSomething that prevents, detects, or limits a threat
RiskLikelihood and impact of a threat, given existing controls
Residual riskWhat is left after mitigations

The 60-minute workflow

Prepare 15 minutes in advance: pick the scope, gather existing architecture docs, and book a room or call with a shared whiteboard (Excalidraw, Miro, FigJam, or a real whiteboard).

00:00-00:10  Scope + diagram         "What are we working on?"
00:10-00:20  Assets + boundaries     actors, data classes, trust boundaries, entry points
00:20-00:45  STRIDE per element      "What can go wrong?"  (timeboxed, 2 min per element)
00:45-00:55  Rate + decide           mitigate / eliminate / transfer / accept
00:55-01:00  Write-up                backlog items, owners, review date

Step 1: Scope and diagram (10 minutes)

State the scope in one sentence: "Order checkout and the new invoice upload flow, excluding the marketing site." Draw a data-flow diagram with the four standard elements:

ElementShape (convention)Examples
External entityRectangleBrowser user, admin, payment provider, partner API
ProcessCircle or rounded boxWeb app, API, worker, Lambda function
Data storeTwo parallel lines or cylinderPostgreSQL, S3 bucket, Redis, queue
Data flowArrow with labelHTTPS request, SQL query, webhook, message

Then draw dashed trust boundaries around groups with the same trust level. Keep the diagram at one level of abstraction, with 5 to 12 elements. If you need more, split into several models.

Step 2: Assets, actors, boundaries (10 minutes)

List what matters. Use a simple table.

AssetWhy it mattersClassification
Customer documentsConfidential business dataHigh
Payment tokens and webhooksFraud, financial lossHigh
Session tokensAccount takeoverHigh
Audit logsForensics, complianceMedium
Service availabilityRevenue and SLAMedium

Name the actors including the malicious ones: anonymous internet user, authenticated customer (tenant A attacking tenant B), malicious or careless insider, compromised third-party service, compromised dependency or CI pipeline, and for AI features, an attacker who controls content the model reads.

Step 3: STRIDE per element (25 minutes)

Walk the diagram element by element. For each, ask the six STRIDE questions (next section). Capture threats as short sentences: "An attacker can X by Y, resulting in Z." Do not solve yet; keep moving. Timebox every element to about two minutes. Park debates in a "needs research" list.

Step 4: Rate and decide (10 minutes)

Give each threat a likelihood and impact, then a decision (see the risk rating section below). Be quick: discuss only when people disagree by more than one level.

Step 5: Write-up (5 minutes)

For every threat you decided to mitigate, create a backlog item or an architecture decision with an owner. Record accepted risks with an owner and a review date. Take a photo of the diagram or export it into the repository. Schedule the next review (for example at the next major change or in six months).

Running the session

  1. Start from the diagram, never from a list of generic threats.
  2. "Yes, and" first, filter later. Do not argue likelihood during brainstorming.
  3. Focus on boundary-crossing flows first; most serious threats live there.
  4. Use concrete attacker goals: "read another tenant's files", "get a refund without paying", "make the assistant leak data".
  5. End on time with decisions, even if coverage is incomplete. A short follow-up session is better than an unfinished marathon.
  6. Rotate the "attacker voice" so quieter members contribute.

STRIDE explained

STRIDE was created at Microsoft in the late 1990s. Each letter is the violation of a security property.

LetterThreatProperty violatedOne-line questionTypical controls
SSpoofingAuthenticationCan someone pretend to be another user, service or device?Strong auth, MFA, mTLS, signed tokens, workload identity
TTamperingIntegrityCan data or code be modified without detection?Input validation, signatures, checksums, immutable logs, least-privilege writes
RRepudiationNon-repudiationCan someone deny an action and we cannot prove otherwise?Audit logs, timestamps, signed events, tamper-evident storage
IInformation disclosureConfidentialityCan data leak to someone who should not see it?Authorization, encryption, minimization, error handling, tenant isolation
DDenial of serviceAvailabilityCan someone make it unavailable or too expensive to run?Rate limits, quotas, timeouts, autoscaling limits, queues, caching
EElevation of privilegeAuthorizationCan someone do something they are not allowed to?Least privilege, deny-by-default, separation of duties, sandboxing

STRIDE per element

Not every threat type applies to every element type. This matrix is the shortcut that makes the 25-minute step manageable.

Element typeSTRIDE
External entityYesYes
ProcessYesYesYesYesYesYes
Data storeYesYes (logs)YesYes
Data flowYesYesYes

Two common variants: STRIDE-per-element (above) walks every element, and STRIDE-per-interaction walks every data flow between two elements (source, destination, flow). Per-interaction produces more precise threats for distributed systems; per-element is faster for a first session.

Worked prompts

Use these as seeds for discussion, adapted to your system.

STRIDEPrompts
SpoofingHow does each service authenticate callers? Could a webhook be forged? Can a user be impersonated by session theft or fixation? Can a client claim another tenant's ID? Can a service identity be impersonated by anything on the same network?
TamperingWho can write to this data store? Can a request body set fields it should not? Are messages in the queue signed or validated? Can an uploaded file be swapped after validation (time-of-check, time-of-use)? Can build artifacts change between test and deploy?
RepudiationDo we record who did what, when, from where? Can an admin edit or delete logs? Would we be able to prove a refund was authorized?
Information disclosureWhat do error messages reveal? What is in logs and backups? Does one tenant's data appear in another's queries, caches or search indexes? Are secrets in environment dumps? Are there predictable URLs to private files?
Denial of serviceWhat is the most expensive operation, and can an anonymous user trigger it? Are uploads, exports, regexes and queries bounded? Can a tenant starve others? Does a dependency outage cascade?
Elevation of privilegeIs every function-level and object-level check on the server? Can a lower role reach admin functions? Does the worker run with more permissions than the API? Can a file upload lead to code execution? Can a container escape reach the node's credentials?

Data-flow diagrams and trust boundaries in text

You do not need a diagramming tool to start. A text diagram is reviewable in a pull request, searchable, and readable by AI agents. Here is a simple notation.

Legend:  [ ] external entity   ( ) process   =| |= data store   --> data flow   ::: trust boundary

 [Customer browser] ---HTTPS---> (CDN / WAF) ---> (Web app + API) ---SQL/TLS---> =| PostgreSQL |=
         :::::::::::::::::::::::::: internet boundary :::::::::::::::::::::::::

Trust boundary rules of thumb

A trust boundary is wherever one of these changes: identity or authority (different credentials or principals), network zone (internet, DMZ, private subnet), ownership (your code versus a vendor), privilege level (user versus admin, container versus host), data sensitivity, or execution context (browser versus server, model output versus trusted code).

Questions to find boundaries:

  1. Where does data come from that we did not generate?
  2. Where does our data go that we do not control?
  3. Where do we switch from one set of credentials to another?
  4. Where does code run on behalf of a lower-privileged party?
  5. For AI systems: where does text from outside the system become input to something that can act?

Diagram levels

LevelShowsUse for
Level 0 (context)The system as one process, actors and external systemsScoping, stakeholders
Level 1Major components and data storesMain threat modeling session
Level 2Internals of one risky component (for example the upload pipeline)Focused follow-up sessions

Common diagramming errors

  • Drawing deployment boxes (servers and VPCs) but not the data flows.
  • Showing only the happy path. Include admin, background jobs, webhooks, CI/CD, and support tooling.
  • Forgetting identity providers, logging pipelines and backups, which are data stores with copies of everything.
  • No labels on arrows. A flow label should include protocol and what data it carries, for example "HTTPS: JWT + upload".
  • A single big "internal network" boundary. Inside the boundary there are almost always more boundaries: tenants, environments, privileged workloads.

Attack trees and abuse cases

STRIDE gives breadth. Attack trees give depth for the few goals that matter most. Start from an attacker goal at the root and decompose into the alternative (OR) or required (AND) ways of achieving it.

GOAL: Read another tenant's documents
 |
 +-- OR: Bypass application authorization
 |     +-- OR: IDOR on /documents/ID (no tenant filter)
 |     +-- OR: Use a stale cached response for a different tenant
 |     +-- OR: Abuse the search index (no per-tenant filter)
 |
 +-- OR: Obtain a valid session of another tenant's user
 |     +-- OR: Phishing / credential stuffing
 |     +-- OR: Session fixation or XSS to steal a token
 |
 +-- OR: Reach storage directly
 |     +-- AND: Learn object key AND bucket policy allows public read
 |     +-- OR: Presigned URL leaked or too long-lived
 |
 +-- OR: Manipulate the AI assistant
       +-- AND: Plant instructions in a document AND assistant has cross-tenant retrieval

Annotate each leaf with difficulty (low, medium, high), detectability, and existing controls. The cheapest path for the attacker is where you invest. Attack trees also feed test plans: each leaf becomes a negative test.

Abuse cases are the user-story form: "As a malicious customer, I want to redeem a coupon repeatedly so I can get free service." Put them in the backlog beside the features they attack, with acceptance criteria such as "second redemption returns an error and logs an event".

Kill chains and misuse thinking

For systems with external attackers, it helps to walk the attack lifecycle: reconnaissance, initial access, execution, persistence, privilege escalation, lateral movement, exfiltration, impact. The MITRE ATT&CK knowledge base catalogues techniques per phase; use it to check detection coverage rather than as a brainstorm starter. For cloud and containers, see ATT&CK for Enterprise and the cloud matrices (verify current versions).

Rating risk without fooling yourself

Numbers attached to threats look scientific. They rarely are. The goal is a consistent, fast prioritization, not a precise measurement.

Simple likelihood times impact

LevelLikelihoodImpact
1 LowNeeds insider knowledge, rare conditions, or significant attacker resourcesMinor inconvenience, no sensitive data, easily recovered
2 MediumNeeds an authenticated user or moderate skill; plausibleLimited data exposure or partial outage; costly but recoverable
3 HighAnonymous, scripted, widely known technique, or already observed in the wildLarge-scale data breach, financial loss, safety, legal or regulatory exposure

Risk score = likelihood x impact (1 to 9). Map: 1 to 2 Low, 3 to 4 Medium, 6 to 9 High.

Impact 1Impact 2Impact 3
Likelihood 33 Medium6 High9 High
Likelihood 22 Low4 Medium6 High
Likelihood 11 Low2 Low3 Medium

Alternatives

MethodWhat it isNotes
DREADDamage, Reproducibility, Exploitability, Affected users, Discoverability (1 to 10 each, averaged)Historically popular, but Microsoft stopped using it due to inconsistent scoring; avoid for new programs
OWASP Risk Rating MethodologyLikelihood factors (threat agent, vulnerability) and impact factors (technical, business), each scored 0 to 9More rigorous; useful when you need defensible numbers
CVSSSeverity of a specific vulnerabilityGood for vulnerabilities in code and dependencies; poor for design-level threats
EPSSProbability that a CVE is exploited in the wildUse for prioritizing dependency findings (verify current model and data)
FAIRQuantitative financial risk analysisHeavy; used by risk teams, not in a 60-minute session
Qualitative H/M/LFacilitated consensusFine for most developer-run sessions

Practical advice: pick one scheme, write its definitions at the top of your template, and use it consistently. Re-rate after mitigations to show residual risk.

The four responses

ResponseMeaningExample
MitigateAdd a control that reduces likelihood or impactAdd per-tenant authorization checks and tests
EliminateRemove the feature or data that creates the threatStop storing card data; use hosted payment fields
TransferShift the risk to another partyUse a payment processor, buy cyber insurance (a financial transfer, not a technical fix)
AcceptConsciously live with itLow-impact denial of service on an internal tool; owner and review date recorded

Eliminate is the underrated one. The cheapest control for a threat is often deleting the data, the endpoint, or the privilege.

Mapping threats to controls

A threat model that ends in a list of threats is half done. Map each to specific, testable controls. This table shows the common mapping from STRIDE to controls and to verification.

STRIDEControl familiesVerification
SpoofingOIDC with PKCE, MFA or passkeys, mTLS between services, workload identity, webhook signaturesAuth tests, token validation tests, config scanning for open endpoints
TamperingParameterized queries, schema validation, signed artifacts, immutable infrastructure, database constraints, S3 object lockSAST, contract tests, signature verification in deploy
RepudiationCentralized structured audit logging, append-only storage, time sync, user and request IDsLog assertion tests, audit review, retention checks
Information disclosureAuthorization with tenant scoping, row-level security, encryption in transit and at rest, field-level encryption, error sanitization, log redactionCross-tenant tests, secret scanning, DAST for leaks
Denial of serviceRate limits, request and upload size caps, timeouts, circuit breakers, queue backpressure, per-tenant quotas, autoscaling limitsLoad tests, limit tests, chaos tests
Elevation of privilegeDeny-by-default policies, role checks on every function, least-privilege IAM, sandboxed workers, non-root containers, no shared admin credentialsAuthorization matrix tests, IaC scanning, penetration tests

Turning threats into backlog items

Each accepted mitigation becomes a story with a clear, testable definition of done:

Title: Enforce per-tenant filter on document search
Threat: T-14 Information disclosure: tenant A reads tenant B documents via search (Risk: High)
Control: Tenant ID filter applied server-side in the search query builder; index per tenant or filtered alias
Acceptance:
  - Cross-tenant search test returns zero results for another tenant's term
  - Query builder rejects missing tenant context
  - Dashboard alert on queries without tenant filter
Owner: search-team   Due: sprint 42   Verification: automated test + quarterly review

Link every backlog item back to the threat ID. When the threat model is reviewed, the status of the items shows how much risk has actually been addressed.

Tooling: from whiteboard to threat modeling as code

Tools support the process; they do not replace thinking. Start with a whiteboard and a Markdown file. Adopt tooling when you need repeatability, version control, or automation.

ToolTypeStrengthsLimits
Whiteboard plus MarkdownManualZero friction; fastest for first sessionsNo automation
OWASP Threat DragonDiagramming and threat tracking (web and desktop)Free, open source, DFD editor with STRIDE suggestions, models stored as JSON files in GitRule suggestions are generic
pytmPython framework (threat modeling as code)Define the system in Python, generate DFDs and a threat report; fits CIRule library is generic; requires Graphviz and a diagram renderer
ThreagileGo tool, YAML-based (threat modeling as code)Declarative model, risk rules, ranking, charts, CI-friendlyLearning curve for the YAML schema
Microsoft Threat Modeling ToolWindows desktop appSTRIDE-oriented, Azure templatesWindows only; check current maintenance status
IriusRisk, ThreatModeler, Security Compass and similarCommercial platformsLibrary of patterns, integrations, compliance mappingCost; model quality still depends on people
Mermaid or PlantUML in MarkdownDiagram as codeRenders in many Git hosts; reviewable in PRsNo threat engine
ATT&CK Navigator, CAPECReference catalogsCheck techniques and attack patternsNot workflow tools

Verify the maintenance status and current capabilities of each tool before you standardize.

Mermaid data-flow diagram in the repository

flowchart LR
  user[Customer browser] -->|HTTPS| edge(CDN and WAF)
  edge --> app(Web app and API)
  app -->|SQL over TLS| db[(PostgreSQL)]
  app -->|S3 API| files[(Object storage)]
  app -->|HTTPS| llm[LLM provider]
  psp[Payment provider] -->|signed webhook| app

Most Git hosts render this when it is placed in a fenced block marked mermaid. The above is shown as plain text here so the page does not need a diagram renderer.

pytm example

# threat_model.py  (pip install pytm; requires Graphviz for diagrams)
from pytm import TM, Server, Datastore, Dataflow, Boundary, Actor, Lambda

tm = TM("Docs SaaS: upload, billing and assistant")
tm.description = "Customer documents, payments via hosted provider, AI assistant over documents"
tm.isOrdered = True

internet = Boundary("Internet")
vpc = Boundary("Application VPC")
vendor = Boundary("Third-party vendors")

user = Actor("Customer")
user.inBoundary = internet

app = Server("Web app and API")
app.inBoundary = vpc
app.isHardened = True
app.sanitizesInput = True
app.encodesOutput = True
app.implementsAuthenticationScheme = True
app.implementsCSRFToken = True

db = Datastore("PostgreSQL")
db.inBoundary = vpc
db.isEncrypted = True
db.isSQL = True

files = Datastore("Object storage")
files.inBoundary = vpc
files.isEncrypted = True

scanner = Lambda("Upload scanner")
scanner.inBoundary = vpc

psp = Server("Payment provider")
psp.inBoundary = vendor

login = Dataflow(user, app, "HTTPS: login and API calls")
login.protocol = "HTTPS"
login.isEncrypted = True
login.authenticatesDestination = True

upload = Dataflow(user, app, "HTTPS: file upload")
upload.protocol = "HTTPS"
upload.isEncrypted = True

store = Dataflow(app, files, "Store uploaded file")
store.protocol = "HTTPS"

hook = Dataflow(psp, app, "Payment webhook")
hook.protocol = "HTTPS"
hook.authenticatesSource = True

query = Dataflow(app, db, "SQL queries")
query.protocol = "PostgreSQL"
query.isEncrypted = True

tm.process()
python threat_model.py --report docs/threat-model.md    # generate findings
python threat_model.py --dfd | dot -Tpng -o docs/dfd.png  # diagram via Graphviz

pytm flags and report templates evolve; check python threat_model.py --help and the project README for the current CLI. Treat the generated findings as prompts for discussion, because rule-based output includes false positives and misses business logic.

Threagile example

# threagile.yaml (abridged; validate against the schema for your Threagile version)
threagile_version: 1.0.0
title: Docs SaaS
author: { name: Platform team }
business_criticality: important

data_assets:
  customer-documents:
    id: customer-documents
    description: Uploaded customer documents
    usage: business
    confidentiality: confidential
    integrity: important
    availability: important
  payment-tokens:
    id: payment-tokens
    description: Provider tokens and webhook payloads
    usage: business
    confidentiality: strictly-confidential
    integrity: critical
    availability: operational

technical_assets:
  web-app:
    id: web-app
    description: Web app and API
    type: process
    usage: business
    technology: web-service-rest
    internet: true
    machine: container
    encryption: none
    data_assets_processed: [customer-documents, payment-tokens]
    communication_links:
      db-queries:
        target: postgres
        protocol: postgresql-encrypted
        authentication: credentials
        authorization: technical-user
        data_assets_sent: [customer-documents]
  postgres:
    id: postgres
    description: Primary database
    type: datastore
    technology: database
    internet: false
    machine: virtual
    encryption: transparent
    data_assets_stored: [customer-documents]

Run it in CI and publish the ranked risks and diagram as build artifacts; fail the build only on new high risks that nobody has triaged. Both pytm and Threagile are good for establishing a baseline and detecting architecture drift, and weak at business logic and abuse cases. Use them with a human session, not instead of one.

A lightweight model file in the repository

docs/threat-model/
  README.md            scope, last review date, owners, risk scale definition
  dfd.md               diagram (Mermaid or text) and element list
  threats.md           threat register (table below)
  decisions.md         accepted risks with owner and review date
  checklist.md         verification: tests and alerts mapped to threats

A threat register as a Markdown table is enough to start:

| ID | Element | STRIDE | Threat | L | I | Risk | Decision | Control / ticket | Owner | Status |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| T-01 | Web app | S | Forged payment webhook marks order paid | 3 | 3 | 9 | Mitigate | Verify HMAC and event ID, JIRA-210 | payments | In progress |

Worked example: a SaaS web app with file uploads, payments and an AI assistant

The system: DocuFlow, a B2B SaaS where customers upload documents (PDFs and images), pay by subscription through a hosted payment provider, and use an AI assistant that answers questions over their documents and can draft emails and create tasks through tools. Multi-tenant, running on a managed Kubernetes cluster with PostgreSQL and object storage.

Step 1: Scope and diagram

Scope: the authenticated product (web app, API, workers), upload pipeline, billing integration, and the AI assistant. Out of scope: the marketing site and internal corporate IT.

                          ::::::::::::::::::::::  INTERNET BOUNDARY  ::::::::::::::::::::::
 [Customer user] --(1) HTTPS login/API--> (Edge: CDN + WAF) --> (Web app + API) ........
 [Tenant admin]  --(2) HTTPS admin------>                           |    |    |
 [Payment provider] --(3) signed webhook--------------------------->|    |    |
                          ::::::::::::::::::::::  VPC / CLUSTER BOUNDARY :::::::::::::::
                                                                    |    |    |
                                    (4) SQL/TLS ---> =| PostgreSQL |=   |    |
                                    (5) presign/put -> =| Object storage |=   |
                                    (6) enqueue ------> =| Job queue |=        |
                                                                    |    |
                          (Worker: scan + extract + embed) <--(7)---+    |
                                   |                                      |
                                   +--(8) text/embeddings--> =| Vector index (pgvector) |=
                                                                          |
                          (Assistant service) <--(9) user question + retrieved chunks
                                   |
                                   +--(10) HTTPS--> [LLM provider]   ::: VENDOR BOUNDARY :::
                                   +--(11) tool calls--> (Tools: send_email, create_task, search_docs)

Assets: customer documents (High), embeddings and extracted text (High, same classification as documents), payment tokens and subscription state (High), session tokens (High), tenant configuration, audit logs, LLM provider API key (High), service availability.

Actors: anonymous visitor, customer user, tenant admin (can invite users, manage billing), malicious customer (tenant A targeting tenant B), compromised customer account, payment provider (trusted but verified), LLM provider (processes data, third party), insider operator, attacker controlling document content.

Trust boundaries: internet to edge; edge to cluster; app to database and storage; app to vendors (payment, LLM); user content to the assistant (content boundary); assistant to tools (privilege boundary).

Step 2: STRIDE sample (excerpt of the threat register)

IDElementSTRIDEThreatLIRisk
T-01Payment webhook (3)SpoofingAttacker forges a "payment succeeded" webhook to unlock a paid plan326
T-02Payment webhook (3)TamperingReplay of a legitimate webhook causes duplicate credit or state change224
T-03Web app and APIElevation of privilegeIDOR: a user fetches a document by ID belonging to another tenant339
T-04Web app and APIElevation of privilegeMass assignment lets a user set their role to admin236
T-05Upload (5)TamperingMalicious file (script in a PDF or SVG, polyglot, zip bomb) is stored and later rendered or processed326
T-06Upload (5)Information disclosurePredictable object keys or long-lived presigned URLs expose files236
T-07WorkerDenial of serviceLarge or crafted files exhaust CPU and memory during extraction, starving other tenants326
T-08WorkerElevation of privilegeDocument parser exploit gives code execution in the worker with access to storage credentials133
T-09Vector index (8)Information disclosureRetrieval does not filter by tenant, so the assistant returns another tenant's text236
T-10Assistant (9)TamperingIndirect prompt injection: a document contains instructions that make the assistant misbehave339
T-11Tools (11)Elevation of privilegeInjected instructions cause the assistant to call send_email with data from other documents236
T-12LLM provider (10)Information disclosureSensitive data sent to a vendor beyond what the contract and users expect; provider retention236
T-13Web app and APIDenial of serviceExpensive assistant queries by one tenant drive LLM costs and rate limits for everyone326
T-14Audit logsRepudiationAdmin deletes a tenant's documents; no record of who did it224
T-15SecretsInformation disclosureLLM API key and DB credentials in environment variables leak via logs or debug endpoint236
T-16CI/CDTamperingMalicious dependency or workflow compromise ships a backdoored image236
T-17Tenant adminSpoofingAccount takeover of a tenant admin through credential stuffing339

Step 3: Decisions and mitigations

ThreatDecisionMitigation and verification
T-01, T-02MitigateVerify the provider's signature using the raw body, check timestamp tolerance, dedupe by event ID in a unique-constrained table. Test: forged, replayed and stale webhooks rejected.
T-03, T-04MitigateTenant-scoped repository layer, row-level security in PostgreSQL as a second layer, DTO allow-lists. Test: cross-tenant matrix generated from the route list. See Multi-Tenant SaaS with PostgreSQL RLS.
T-05MitigateAllow-list content types by magic bytes, not extension; strip active content; serve downloads from a separate cookieless domain with Content-Disposition: attachment and nosniff; scan with antivirus in an isolated worker; render previews server-side to safe images.
T-06MitigateRandom, tenant-prefixed object keys; presigned URLs with short TTL (minutes) and content-length constraints; no public bucket access; bucket policy blocking non-TLS.
T-07, T-08MitigateRun workers in sandboxed containers (non-root, read-only filesystem, no network egress except to storage), CPU and memory limits, per-file size and page limits, timeouts, per-tenant job concurrency; workers use scoped credentials via workload identity.
T-09MitigateTenant ID is a mandatory filter parameter in the retrieval API (not model-supplied); RLS on the embeddings table; automated cross-tenant retrieval test with canary strings.
T-10, T-11Mitigate and reduceTreat all retrieved text as untrusted data; separate instructions from content; limit tool permissions; no tool that sends data outside the tenant without a human confirmation; output filtering and egress controls. See the prompt injection guide.
T-12Mitigate and transferData processing agreement with zero-retention terms where available (verify the provider's current terms); minimize context; document in privacy notice; allow tenants to opt out of AI features.
T-13MitigatePer-tenant token budgets and rate limits; cost alerts; queue assistant jobs with fair scheduling.
T-14MitigateAppend-only audit log of admin and destructive actions with actor, tenant, target, request ID; stored separately with restricted delete rights.
T-15MitigateSecrets in a manager with workload identity, no secrets in env dumps; log redaction. See Secrets Management in 2026.
T-16MitigateLockfiles, pinned CI actions, dependency review, SBOM, signed images; see the supply chain section of the OWASP guide.
T-17MitigatePasskeys or TOTP required for tenant admins, rate limiting, breached-password checks, new-device notifications, step-up authentication for billing and export.

Step 4: An attack tree for the AI assistant

GOAL: Exfiltrate another document's content through the assistant
 |
 +-- AND: Get malicious instructions into the model context
 |     +-- OR: Upload a document containing hidden instructions
 |     +-- OR: Shared document from an external party
 |     +-- OR: Web content fetched by a browsing tool
 |
 +-- AND: Assistant has a channel to send data out
       +-- OR: send_email tool to an arbitrary address            -> restrict recipients, confirm
       +-- OR: Markdown image or link rendering to an attacker URL  -> block external images, sanitize
       +-- OR: Tool result containing attacker-controlled URL fetch -> egress allow-list

Because the attack needs both branches, removing either one breaks the chain. Cutting the exfiltration channel (confirmation on outbound actions, no external image rendering, egress control) is usually more reliable than trying to detect every malicious instruction.

Step 5: Residual risk and review

Residual riskOwnerReview
Prompt injection can still degrade answer quality inside one tenantProduct + ML leadQuarterly, and on any new tool
Zero-day in document parsersPlatformOn parser CVE, monthly dependency review
LLM vendor outage or data handling changeEngineering managerOn vendor notification

Resulting backlog (sample)

TicketPriorityLinked threats
Verify and dedupe payment webhooksP0T-01, T-02
Tenant-scoped repository layer and RLSP0T-03, T-09
Sandbox document workersP1T-05, T-07, T-08
Confirmation gate on outbound assistant actionsP0T-10, T-11
Per-tenant AI budgets and rate limitsP1T-13
Audit log for admin actionsP1T-14
Enforce MFA for tenant adminsP1T-17

An hour of modeling produced seven specific work items and several design decisions, including two that removed risk (no outbound tool without confirmation, no public buckets), which no scanner would have suggested.

LINDDUN for privacy threat modeling

STRIDE focuses on security. LINDDUN is a privacy-oriented methodology developed at KU Leuven, with the same structure (DFD plus threat categories) but privacy threat types. It helps with GDPR-style obligations such as data minimization, purpose limitation and data subject rights.

LetterThreatQuestion
LLinkingCan records be linked across datasets or sessions to build a profile?
IIdentifyingCan a person be identified from supposedly anonymous data?
NNon-repudiationCan a person be forced to be unable to deny an action they want to deny (for example, whistleblowing)?
DDetectingCan an observer detect that someone is using the system or that an item exists?
DData disclosureIs personal data exposed to parties who should not have it?
UUnawareness and unintervenabilityDo people know what is collected, and can they access, correct, delete or object?
NNon-complianceDoes processing violate policy, law, consent or contract?

Applying it

  1. Start from the same DFD. Mark every data store and flow that contains personal data, and label the categories (identifiers, contact, financial, health, content, behavioral).
  2. For each, ask the LINDDUN questions. Examples: analytics events with a user ID and a device fingerprint are linkable; a support tool showing full documents violates data minimization; a "delete my account" flow that leaves data in backups, search indexes, embeddings and logs fails unintervenability.
  3. Map mitigations: data minimization, pseudonymization, retention limits, encryption, access controls and purpose-based access, consent records, data subject request automation, and DPIA (data protection impact assessment) where required.

Example privacy findings for DocuFlow

FindingCategoryMitigation
Embeddings of deleted documents remain in the vector indexNon-compliance, unintervenabilityDeletion pipeline removes object, extracted text, embeddings and cached answers; verification job
Support staff can open any tenant's documentsData disclosureJust-in-time support access with tenant consent and audit trail
LLM prompts logged in full for debuggingData disclosureLog prompt hashes and metadata only; short retention for redacted samples
Analytics tool receives user emailIdentifying, linkingSend pseudonymous ID; no document names
Backups retain deleted data for 35 daysNon-complianceDocument retention in privacy notice; crypto-shredding with per-tenant keys where feasible

Privacy law is jurisdiction-specific. Use LINDDUN to find issues, and involve your privacy officer or counsel for obligations; do not treat this post as legal advice.

Threat modeling AI and agent systems

AI features introduce new elements to the diagram: a model (a process whose behavior depends on untrusted input), a context window (a mixed-trust data store), tools (privileged actions), memory (persistent state that outlives sessions) and retrieval (a data flow from stores into the model). The standard STRIDE lens still applies, plus a few special rules.

What changes

  1. Instructions and data share one channel. The model cannot reliably distinguish a system prompt from text in a retrieved document. Any content the model reads is a potential command channel.
  2. The model is a confused deputy. It acts with the privileges of its tools, on behalf of whoever last influenced its context.
  3. Outputs are untrusted. Model output going into a shell, SQL, HTML, or another agent is an injection vector like user input.
  4. Behavior is non-deterministic. A control that works 95 percent of the time is not a control; design for the case where the model does the worst allowed thing.

Agent-specific STRIDE prompts

STRIDEAI and agent threatsMitigations
SpoofingAgent acts under a user's identity without proof of user intent; one agent impersonates another in multi-agent flows; fake tool serverPer-user delegated tokens, agent identities, signed messages between agents, pinned and reviewed tool servers
TamperingPrompt injection (direct and indirect); poisoned documents or memory; manipulated tool results; model supply chain (weights, plugins, skills)Content isolation, provenance labels, memory validation, review of skills and servers, pin versions and checksums
RepudiationNo record of why the agent took an action; cannot prove which prompt or document led to a decisionLog prompts, retrieved sources, tool calls and approvals (with redaction); link to a trace ID
Information disclosureCross-tenant retrieval; data leakage via rendered links or images; secrets in prompts; verbose tool errors; vendor retentionTenant filters outside model control; block external rendering; secret-free contexts; DPAs; output filtering
Denial of serviceToken exhaustion, infinite agent loops, expensive tool calls, retrieval of huge contexts ("denial of wallet")Budgets, step limits, timeouts, rate limits per tenant, loop detection
Elevation of privilegeExcessive agency: tools with write or send powers; agents with shell, filesystem or cloud credentials; tool chaining that bypasses a boundaryLeast-privilege tools, human confirmation for destructive or outbound actions, sandboxes, per-task credentials

Reference lists to cross-check

  • OWASP Top 10 for LLM Applications (verify the current edition): prompt injection, sensitive information disclosure, supply chain, excessive agency, and more.
  • MITRE ATLAS: an ATT&CK-style knowledge base of adversary tactics against AI systems.
  • NIST AI Risk Management Framework and its generative AI profile, for governance-level mapping.
  • MCP security guidance from the Model Context Protocol documentation, for tool server threats (verify the current spec).

The lethal trifecta check

A practical test for an agent design: does it combine all three of access to private data, exposure to untrusted content, and an ability to communicate externally (send email, make web requests, render remote images)? If yes, there is a credible exfiltration path from a single poisoned input. Remove at least one leg: drop external communication, restrict private data access for this agent, or isolate untrusted content processing in a low-privilege agent that cannot call dangerous tools.

Untrusted content ---> [Quarantined agent: no tools, no private data] ---> structured summary
                                                                              |
                                                          (schema-validated, plain data only)
                                                                              v
Private data + tools ---> [Privileged agent: sees only validated summary] ---> actions (with confirmation)

This split (a quarantined reader and a privileged actor, exchanging only validated structured data) is a design-level mitigation that does not rely on spotting malicious text.

Add these to your DFD

  • Mark the model as a process on the boundary between trusted and untrusted content.
  • Draw each tool as a separate process with its own identity and permissions.
  • Draw memory and vector stores as data stores with a note on who can write to them.
  • Mark every flow where text from a lower-trust source enters the context.

Making threat modeling part of the SDLC

A model that lives in a one-off workshop decays. Embed it into the workflow so it takes minutes, not days.

StageActivityArtifact
Discovery and designAdd a "Security and threat model" section to the design document or RFCShort DFD plus top threats
Design reviewReviewers ask: what changed in trust boundaries, data, actors?Checklist in the template
ImplementationMitigations are tickets with acceptance tests; abuse cases in the backlogLinked issues
Pull requestPR template asks "Does this change a trust boundary or add an entry point? If yes, update the model"Checkbox and link
TestingNegative tests mapped to threats; DAST and fuzzing for entry pointsTest names reference threat IDs
ReleaseVerify mitigations exist (feature flags, config)Release checklist
OperationsAlerts for detection controls; incident reviews feed back into the modelRunbooks, post-incident updates
PeriodicReview models for critical systems every 6 to 12 months, or after major changesUpdated date and diff

Design review template (paste into your RFC template)

## Security and threat model

**Scope:** (one sentence)
**Data classification:** (public / internal / confidential / restricted) and personal data involved
**Diagram:** (link or embedded DFD with trust boundaries)

**Assets:** (list)
**Actors (including malicious):** (list)
**Entry points:** (list)

**Top threats (STRIDE):**
| ID | Threat | Risk | Decision | Control / ticket |
| --- | --- | --- | --- | --- |

**Accepted risks:** (with owner and review date)
**Verification:** (tests, alerts, config checks mapped to threat IDs)
**Open questions:**

Pull request prompts

- [ ] This change does not add or modify an entry point, trust boundary, data store, or external integration
- [ ] OR: the threat model in docs/threat-model was updated (link)
- [ ] New endpoints have authorization tests for another tenant and an unauthenticated caller
- [ ] New user-controlled input has size, rate and type limits
- [ ] New outbound requests, tools or permissions were reviewed for least privilege

Metrics that matter

MetricWhy
Percent of features with a model or a documented reason to skipCoverage
Time from threat identification to mitigation shippedResponsiveness
Number of design-level findings per modelValue signal; zero repeatedly suggests shallow sessions
Findings in production later traced to a modeled threat versus an unmodeled oneQuality of the process
Open accepted risks past their review dateHygiene

Scaling to many teams

Provide a starter library: reference DFDs for common patterns (web app plus API, event-driven pipeline, file upload, third-party integration, AI assistant) and pre-written threat and control sets per pattern. Teams then modify rather than start from scratch. Train a few "security champions" per group to run sessions. Keep the central security team for review of critical systems and for cross-cutting decisions.

Where this usually goes wrong

  1. Starting with threats instead of a diagram. You end up with a generic list unrelated to the system.
  2. Modeling too big. "The whole platform" in one session means nothing gets examined. Pick a flow.
  3. Only external attackers. Include malicious tenants, insiders, compromised dependencies, and the model itself.
  4. Confusing vulnerabilities with threats. "Outdated library" is a vulnerability; "attacker achieves code execution in the worker through a document parser bug" is a threat in context.
  5. No decisions. A list of threats with no owner or decision is noise.
  6. Treating the output as a compliance document. If nobody reads it a month later, it was theatre.
  7. Overprecise scoring. Debating whether a threat is a 6.2 or a 6.8 wastes the session.
  8. Ignoring the supply chain and operations. CI/CD, backups, support tooling and monitoring are part of the system.
  9. Skipping verification. A mitigation without a test or check silently disappears in the next refactor.
  10. One-and-done. The model must change when the architecture does.
  11. Letting tools think for you. Automated rule output is a checklist for discussion, not a verdict.
  12. No AI lens for AI features. Applying only classic web threats to an agent misses the main risks.

When to skip this, or use a lighter version

  • Trivial changes. Copy edits, styling, or a change within an already-modeled boundary do not need a session. Use a checklist.
  • No one with system knowledge in the room. A model by outsiders who do not know the architecture produces fiction. Wait or do homework first.
  • You have not decided the architecture. If the whole design is in flux, do a lightweight context-level model and revisit.
  • Heavy formal methodologies for a small team. PASTA, full quantitative risk analysis (FAIR), and commercial platforms are valuable in large regulated environments; they are overkill for a five-person startup's first model. Start with STRIDE.
  • As a substitute for testing. Threat modeling finds missing controls; it does not prove that implemented ones work. Pair with the scanning and testing described in the OWASP guide.
  • When the organization will not act on the results. First secure agreement that high-risk findings get prioritized; otherwise the activity breeds cynicism.
  • Blindly automating with an AI assistant. An LLM can help generate candidate threats from a DFD and speed up the write-up, but it will miss context and sometimes invent components. Use it as a brainstorming aid with human review, and never paste sensitive architecture details into a service you do not trust with them.

A reusable template

Copy this into docs/threat-model/README.md and fill it in. Keep it to two pages.

# Threat model: <system or feature>

- Date: YYYY-MM-DD    Participants: <names/roles>    Facilitator: <name>
- Next review: <date or trigger>    Status: <draft | agreed | superseded>

## 1. Scope
In scope: ...
Out of scope: ...
Assumptions: ... (for example "the cloud provider's control plane is trusted")

## 2. Diagram
<DFD with trust boundaries, element IDs, flow IDs>

## 3. Assets and classification
| Asset | Classification | Where stored / flows |

## 4. Actors
| Actor | Trust level | Capabilities |

## 5. Entry points
| ID | Entry point | Authentication | Notes |

## 6. Risk scale
Likelihood 1-3, Impact 1-3, risk = L x I; High >= 6, Medium 3-4, Low <= 2.

## 7. Threat register
| ID | Element or flow | STRIDE | Threat statement | L | I | Risk | Decision | Control / ticket | Owner | Verification |

## 8. Accepted risks
| ID | Rationale | Owner | Review date |

## 9. Privacy (LINDDUN) findings
| ID | Category | Finding | Mitigation |

## 10. AI and agent findings (if applicable)
| ID | Finding | Mitigation |

## 11. Actions
| Ticket | Priority | Threat IDs | Owner | Due |

## 12. Review log
| Date | Change | Who |

Threat statement format

Write each threat so it is testable:

[Actor] can [action / technique] against [element or flow], resulting in [impact on asset],
because [missing or weak control].

Example:
A malicious tenant user can request /api/documents/ID with another tenant's ID,
resulting in disclosure of confidential documents,
because the repository query is not scoped by tenant.

A prompt for AI-assisted brainstorming (with human review)

You are helping a development team prepare for a threat modeling session.
Given this data-flow diagram (elements, flows, trust boundaries), list candidate STRIDE threats per element and per boundary-crossing flow.
For each: one sentence in the format "[Actor] can [action] against [element], resulting in [impact]", the STRIDE letter, and a suggested control.
Do not invent components that are not in the diagram. Mark any assumption you made.
Do not provide step-by-step exploitation instructions; focus on design weaknesses and mitigations.

Treat the response as a list of prompts to discuss, and delete anything the team cannot map to a real element.

A first-session lab

A practical exercise for a team that has never modeled before. Pick a small feature, for example "password reset by email" or "invite a teammate".

  1. Draw (10 min). Browser, web app, database, email provider. Mark the trust boundaries. Label flows (HTTPS request with email, email with reset link, HTTPS request with token).
  2. List assets (3 min). Account access, reset tokens, user email addresses.
  3. STRIDE (20 min). For the reset token flow, expect to find: token guessability (spoofing), token reuse and long lifetime (tampering and replay), account enumeration via different responses (information disclosure), email flooding (denial of service), no log of resets (repudiation), reset without invalidating sessions (elevation of privilege).
  4. Decide (10 min). High-entropy single-use token stored hashed, short expiry, uniform responses, rate limits per account and IP, audit log events, invalidate sessions on reset, notify the user.
  5. Write tickets (5 min). Each mitigation with acceptance tests.
  6. Retro (2 min). What was unclear? What did we assume? What will we change in the next session?

You will have a real design improvement and a reusable pattern after one hour.

Questions that come up

How long should a threat modeling session take? Sixty minutes for a focused feature, up to two hours for a major component. Longer sessions should be split by flow.

Do we need a security expert? Not to start. Developers who know the system find most of the valuable threats. A security engineer helps with attacker perspective and calibration, and should review models of critical systems.

STRIDE, PASTA, or something else? STRIDE for developer-driven design reviews. PASTA is a heavier, risk-centric process for organizations that want business-impact analysis. LINDDUN for privacy. Attack trees for deep dives on one goal. Combine them as needed.

How is threat modeling different from a penetration test? It happens earlier, at design level, finds missing controls, and does not need a running system. A penetration test validates the implemented system from the outside. They complement each other.

Can AI do the threat model for us? It can speed up brainstorming and documentation, but it cannot know your system's real data flows, business rules or controls, and may hallucinate components. Use it as an assistant to a human-led session.

What about third-party SaaS that we cannot inspect? Model the boundary: what data you send, what credentials you give, what happens when the vendor is compromised or unavailable, and what the contract and certifications promise. Mitigate with minimization, scoped credentials, and exit plans.

Sources and docs