Threat modelling for a small team: draw the feature, ask what can go wrong, record what you decide
Threat modelling is a design activity.
A few people draw what they are building, ask what can go wrong wherever data crosses a line of trust, decide what to do about each answer and write the decisions down. This guide covers the diagram, trust boundaries, STRIDE as a set of prompts, abuse cases, the four decisions, and how a decision becomes a requirement with an owner and a test. It comes with a worked data-flow diagram and threat register for an invented booking application, a blank register and a small checker you can run.
In this guide
Worked data-flow diagram and threat register, with a register checker
An illustration written for this page, not a client's system. Parts 1 to 4 are a data-flow diagram written as text for an invented pottery studio's booking application, a thirteen-row threat register that ties each threat and abuse case to a decision and an owner by role, and each mitigation or removal to a security requirement and an acceptance check with a pass and a fail condition, a blank register with its columns explained, and a list for checking the model against the build.
How to use itHide the instructions
Parts 5 to 8 are a Node.js kit with nothing to install: the register as a data file, a script that reports gaps in it, and five acceptance criteria as tests that fail on the first version of a small invented handler and pass on the second, with output recorded on Node.js 26.0.0.
threat-modelling.txt
WORKED DATA-FLOW DIAGRAM AND THREAT REGISTER FOR A SMALL BOOKING APPLICATION
Written for this page. Greenware Studio, its booking application, its staff and every decision below are invented. They are not a client's system and not a client's result.
Parts 1 to 4 need only a text editor: a data-flow diagram written as text, a threat register with one row per threat, a blank register for your own feature, and a list for checking the model against what was built. Parts 5 to 8 are a small kit you can run: the same register as a data file, a script that reports gaps in it, and five of its acceptance criteria written as tests.
Every decision, requirement and acceptance criterion in the register is this page's worked example for an invented business. None of them is what a standard asks for, with one marked exception: the requirement in T9 cites ASVS 5.0 requirements 8.2.1 and 8.3.1 (both Level 1). Rewrite all of it for your own feature before you rely on it.
==== PART 1. THE DATA-FLOW DIAGRAM, WRITTEN AS TEXT ====
Greenware Studio is an invented pottery studio that sells seats in its classes online. A customer books without an account, pays on a payment provider's hosted page and gets an email with a link for managing the booking. Staff sign in as an instructor or as the studio owner.
The numbered list below is the diagram. It uses the five kinds of element in Microsoft's training unit on data-flow diagram elements: external entities, processes, data stores, data flows and trust boundaries. Copy it, then replace every line with your own.
System: Greenware Studio class bookings (invented for this page). Last reviewed on 2026-11-14.
EXTERNAL ENTITIES (outside the studio's direct control)
E1 Customer. Uses a browser. Has no account.
E2 Staff member. Uses a browser. Signs in as an instructor or as the studio owner.
E3 Payment provider. Another company. Hosts the checkout page, takes refund requests and sends payment webhooks.
E4 Email provider. Another company. Delivers the application's email.
PROCESSES (the studio's own running code)
P1 Booking site. Public pages and the booking API.
P2 Staff area. Class rosters, attendance and refunds.
P3 Payment webhook endpoint. Receives the payment provider's webhooks.
P4 Scheduled jobs. Run on a timer. Send reminder emails.
DATA STORES
D1 Bookings database. Classes, bookings, customers' names, email addresses and phone numbers, staff accounts.
D2 Secrets store. Payment API key, webhook signing secret, email API key, session signing key.
D3 Application log. One entry per event, written by every process.
DATA FLOWS (from -> to, what moves, and the boundary crossed)
F1 E1 -> P1. Booking request: class, number of seats, name, email address, phone number. Crosses TB1.
F2 P1 -> D1. Read the seats left. Write the unpaid booking. Crosses no boundary.
F3 P1 -> E3. Create a checkout session: booking id and amount, sent with the payment API key. Crosses TB3.
F4 E3 -> P3. Webhook: payment succeeded, with the booking id, the amount and a signature. Crosses TB1 and TB3.
F5 P3 -> D1. Mark the booking paid. Crosses no boundary.
F6 P3 -> E4. Confirmation email: first name, class, time and the manage link, sent with the email API key. Crosses TB3.
F7 E1 -> P1. Manage-link request: the token from the email, to view, cancel or move one booking. Crosses TB1.
F8 E2 -> P2. Staff sign-in, then roster, attendance and refund requests. Crosses TB1 and TB2.
F9 P2 -> D1. Read rosters. Write attendance and refunds. Crosses no boundary.
F10 P2 -> E3. Refund request: payment id and amount, sent with the payment API key. Crosses TB3.
F11 P4 -> D1. Read tomorrow's bookings. Crosses no boundary.
F12 P4 -> E4. Reminder email: first name, class and time, sent with the email API key. Crosses TB3.
F13 P1, P2, P3, P4 -> D2. Read secrets when the application starts. Crosses no boundary.
F14 P1, P2, P3, P4 -> D3. Write log entries. Crosses no boundary.
F15 P4 -> E4. Planned and then removed (see T11): a nightly email to the owner with a file of every customer's name, email address and phone number. Crosses TB3.
TRUST BOUNDARIES
TB1 Internet edge. Between anything a browser or another company's server sends and the studio's application. Crossed by F1, F4, F7 and F8.
TB2 Staff line. Between what any visitor may do and what only signed-in staff may do, and inside the staff area between an instructor and the studio owner. Crossed by F8.
TB3 Third-party line. Between the studio's application and services that other companies run. Crossed by F3, F4, F6, F10, F12 and F15.
ASSUMPTIONS (written down so that someone can check them)
A1 The application, its database, its secrets store and its log run in one hosting account, and only the application can reach the database. So F2, F5, F9, F11, F13 and F14 cross no trust boundary in this model.
A2 Customers type card details into the payment provider's hosted checkout page. No card number, expiry date or security code is sent to P1.
A3 Only the studio owner and the lead developer can read the secrets store (D2) in the hosting account.
A SKETCH OF THE ZONES
The list above is the diagram. This sketch only shows which side of each line things sit on.
OUTSIDE THE STUDIO'S CONTROL
(E1) Customer
(E2) Staff member
(E3) Payment provider
(E4) Email provider
==== TB1 Internet edge ====
in: F1 F4 F7 F8
THE STUDIO'S APPLICATION
(P1) Booking site
(P3) Webhook endpoint
(P4) Scheduled jobs
.... TB2 Staff line ....
(P2) Staff area
in: F8
........................
THE STUDIO'S DATA STORES
=D1= Bookings database
=D2= Secrets store
=D3= Application log
F2 F5 F9 F11 F13 F14
cross no boundary (A1)
==== TB3 Third-party line ====
out to (E3): F3 F10
out to (E4): F6 F12 F15
in from (E3): F4
==== PART 2. THE THREAT REGISTER ====
Method: the six STRIDE categories (spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege), asked as questions of each flow that crosses a trust boundary. The guide on this page gives Microsoft's definition of each category. One threat, T13, sits inside a zone and crosses no boundary: the questions are a way to find threats, not a rule about where threats are.
How to read a row: the threat's id and category, the element or flow it applies to and the boundary that flow crosses, the threat in one sentence, the abuse case, the decision, and what that decision needs. A mitigation or a removal needs a requirement, an owner and an acceptance check with a pass and a fail condition. An accepted risk needs an owner and a review date. A transfer needs the party that takes it on and an owner for what stays behind.
T1 Denial of service. Applies to F1 (Customer to Booking site). Crosses TB1 (Internet edge).
Threat: Someone holds every seat in a class with bookings they never pay for, so real customers see the class as full.
Abuse case: A person, or a script, starts bookings for all the seats in a popular class and abandons each one at the payment step, again and again.
Decision: MITIGATE.
Requirement: An unpaid booking holds its seats for 15 minutes. After that the seats are released and the booking can no longer be paid.
Owner: Backend developer.
Acceptance check: Start a booking for 2 seats in a class with 8 seats and do not pay. Read the seats left straight away, and again once 16 minutes have passed on the application's clock.
Pass: 6 seats left, then 8.
Fail: Still 6 seats left after 16 minutes.
T2 Tampering. Applies to F1 (Customer to Booking site). Crosses TB1 (Internet edge).
Threat: The amount to charge is taken from the booking request, so a customer can change it before it is sent.
Abuse case: A customer edits the request in the browser and sends an amount of 1 cent for two seats.
Decision: MITIGATE.
Requirement: The server works out the amount from the class price it holds and the number of seats. An amount sent in the request is ignored.
Owner: Backend developer.
Acceptance check: Send a booking request for 2 seats in a class priced at 9500 cents a seat, with an amount of 1 cent added to the request.
Pass: The booking is stored with 19000 cents due.
Fail: The booking is stored with any other amount due.
T3 Information disclosure. Applies to F3 (Booking site to Payment provider) and F10 (Staff area to Payment provider). Crosses TB3 (Third-party line).
Threat: The payment API key leaks from the repository, a log or a laptop, and whoever holds it can ask the provider for refunds in the studio's name.
Abuse case: Someone finds the key in an old commit or a pasted error message and uses it to send refund requests.
Decision: MITIGATE.
Requirement: The payment API key is kept only in the hosting account's secrets store (D2), and a secret scan runs on every push and fails the build when it finds a key.
Owner: Lead developer.
Acceptance check: Push a test branch that contains a made-up string in the provider's key format.
Pass: The build fails and names the file.
Fail: The build passes.
T4 Spoofing. Applies to F4 (Payment provider to Payment webhook endpoint). Crosses TB1 (Internet edge) and TB3 (Third-party line).
Threat: Anyone on the internet can send the webhook endpoint a message that claims a booking was paid.
Abuse case: A customer starts a booking, skips the payment and posts a made-up payment-succeeded message for their booking id to the webhook address.
Decision: MITIGATE.
Requirement: The webhook endpoint accepts a message only when its signature, checked with the webhook signing secret over the exact text received, is valid, and only when the amount in the message equals the amount due on the booking. Anything else is refused and changes nothing.
Owner: Backend developer.
Acceptance check: Post a payment-succeeded message for an unpaid booking with no signature, then with a signature made with the wrong secret.
Pass: Both are refused with status 400 and the booking is still unpaid.
Fail: Either message is accepted, or the booking is marked paid.
T5 Information disclosure. Applies to F6 (Payment webhook endpoint to Email provider) and F12 (Scheduled jobs to Email provider). Crosses TB3 (Third-party line).
Threat: Every email hands customers' details to another company and to whoever can read the inbox, and each extra field sent is one more that can leak.
Abuse case: Someone with access to a customer's inbox, or to the email provider's message log, reads phone numbers and staff notes that the email did not need to carry.
Decision: MITIGATE.
Requirement: Confirmation and reminder emails carry the customer's first name, the class, its time and, for a confirmation, the manage link. They carry no surname, no phone number and no staff notes.
Owner: Backend developer.
Acceptance check: In the test environment, capture what the application hands to the email provider for one confirmation and one reminder.
Pass: Each message holds only the fields the requirement lists.
Fail: Either message holds a surname, a phone number or a staff note.
T6 Spoofing. Applies to F7 (Customer to Booking site). Crosses TB1 (Internet edge).
Threat: The manage link is the only thing that shows who the customer is, so anyone who can guess a token or reuse an old one can act as that customer.
Abuse case: Someone changes characters in a manage link to try other bookings, or uses an old link after the class has run.
Decision: MITIGATE.
Requirement: A manage token is 32 random bytes from the platform's cryptographic random source, is stored only as a hash, works for one booking and stops working when the class starts. A wrong or expired token gets the same 404 as an address that does not exist.
Owner: Backend developer.
Acceptance check: Request the manage page with a token changed by one character, and with a real token once the class start time has passed on the application's clock.
Pass: Both requests get status 404 and no booking details.
Fail: Either request shows or changes a booking.
T7 Information disclosure. Applies to F7 (Customer to Booking site). Crosses TB1 (Internet edge).
Threat: Anyone who is forwarded a confirmation email holds a working manage link.
Abuse case: A customer forwards the confirmation to a friend who is coming along, and the friend, or anyone else that email reaches, cancels or moves the booking.
Decision: ACCEPT. Owner: Studio owner. Review date: 2027-05-14.
Note: Customers have no accounts, so the link is the only credential. The manage page shows a first name, the class and its time, and lets the holder cancel or move that one booking. Staff can restore a cancelled booking from the roster. Look at this again if customer accounts are added, and on the review date at the latest.
T8 Spoofing. Applies to F8 (Staff member to Staff area). Crosses TB1 (Internet edge) and TB2 (Staff line).
Threat: A staff password that is guessed, phished or reused from another site lets an outsider sign in to the staff area.
Abuse case: Someone tries passwords from a leaked list against the owner's email address on the staff sign-in page.
Decision: MITIGATE.
Requirement: Staff sign-in needs a password and a second factor.
Owner: Lead developer.
Acceptance check: Sign in to a staff test account with the right password and no second factor, then request a roster.
Pass: The roster request is refused with status 401.
Fail: The roster is returned.
T9 Elevation of privilege. Applies to F8 (Staff member to Staff area). Crosses TB2 (Staff line).
Threat: The refund button is hidden from instructors, but the refund request itself is open to any signed-in staff member.
Abuse case: An instructor, or someone using an instructor's session, sends the refund request directly instead of using the screen.
Decision: MITIGATE.
Requirement: Every staff request checks the signed-in person's role on the server, and a refund needs the owner role. Needing the owner role for a refund follows ASVS 5.0 requirement 8.2.1 (Level 1), which asks that function-level access is restricted to consumers with explicit permissions. Checking the role on the server follows requirement 8.3.1 (Level 1), which asks that authorisation rules are enforced at a trusted service layer and do not rely on controls that an untrusted consumer could manipulate, such as client-side JavaScript.
Owner: Backend developer.
Acceptance check: Send a refund request for a paid booking from an instructor's session.
Pass: Status 403 and no refund recorded.
Fail: Any other status, or a refund recorded.
T10 Repudiation. Applies to F8 (Staff member to Staff area). Crosses TB2 (Staff line).
Threat: A refund is issued and nobody can show which staff member issued it.
Abuse case: A staff member refunds a friend's booking from a login the whole studio shares, and later says it was not them.
Decision: MITIGATE.
Requirement: Each staff member has their own account, and every refund writes a log entry with the staff account, the booking, the amount and the time.
Owner: Backend developer.
Acceptance check: Issue one refund from the owner's test account, then read the log.
Pass: One refund entry, and it names that account, the booking, the amount and a time.
Fail: No refund entry, more than one, or an entry with any of the four missing.
T11 Information disclosure. Applies to F15 (Scheduled jobs to Email provider). Crosses TB3 (Third-party line).
Threat: A nightly email would put every customer's name, email address and phone number in one file, in an inbox and at the email provider.
Abuse case: Someone who gets into the owner's mailbox, or who is sent the file by mistake, has the studio's whole customer list.
Decision: REMOVE. The nightly emailed customer export (F15) is taken out of the release. The roster screen in the staff area covers the need it was meant for.
Requirement: The application has no export route and no scheduled export job.
Owner: Lead developer.
Acceptance check: Request the export address from the owner's session, and list the scheduled jobs.
Pass: Status 404, and the only scheduled job is the reminder emails.
Fail: A file is returned, or an export job is listed.
T12 Information disclosure. Applies to F3 (Booking site to Payment provider). Crosses TB3 (Third-party line).
Threat: Card details handled by the studio's own application could be read from its requests, its log or its database.
Abuse case: Someone who gets into the application or its log looks for stored card numbers.
Decision: TRANSFER to Payment provider. Owner of what stays behind: Lead developer.
Note: Customers type card details into the payment provider's hosted checkout page (assumption A2), and the provider's agreement with the studio covers storing and processing them. What stays with the studio: the amount it asks the provider to charge (T2), the payment API key (T3) and the webhook endpoint (T4).
T13 Information disclosure. Applies to D3 (Application log). Crosses no boundary.
Threat: The application log collects customers' details and working manage tokens, and more people can read the log than can read the database.
Abuse case: Someone with access to the log viewer copies a manage token or a customer's phone number out of a logged request.
Decision: MITIGATE.
Requirement: A log entry carries the booking id and the name of the event. It never carries a manage token, an email address, a phone number or the text of a request.
Owner: Backend developer.
Acceptance check: In the test environment, make one booking and open its manage link, then search the log for the test customer's email address, phone number and token.
Pass: None of the three is found.
Fail: Any of the three is found.
==== PART 3. A BLANK REGISTER FOR YOUR OWN FEATURE ====
Draw your diagram first, in the shape of Part 1. Then fill one row per threat.
THE COLUMNS
Id A short name such as T1. A requirement, a test and a log line can all point at it. Never reuse one.
Applies to The element or flow the threat is about, by its id on your diagram.
Boundary crossed The trust boundary that flow crosses, or "none" for a threat inside one zone.
Category The STRIDE category you were asking about when the threat came up.
Threat One sentence: what could go wrong.
Abuse case Who tries what, in plain words. Enough for a tester to write the check, and no more.
Decision Mitigate, accept, remove or transfer.
Requirement For mitigate and remove: what has to be true, in words someone can check.
Owner A role, not a person's name. For mitigate and remove, the role that builds it. For accept, the role that accepts it. For transfer, the role that owns what stays behind.
Acceptance check For mitigate and remove: what to do to check the requirement.
Pass The result that means the requirement is met.
Fail The result that means it is not.
Review date For accept: the date the decision is looked at again.
Transferred to For transfer: the party that takes it on.
Note For accept, the reason and what would reopen it. For remove, what was taken out. For transfer, what stays with you.
A BLANK ROW (copy one per threat)
Id:
Applies to:
Boundary crossed:
Category:
Threat:
Abuse case:
Decision:
Requirement:
Owner:
Acceptance check:
Pass:
Fail:
Review date:
Transferred to:
Note:
==== PART 4. CHECKING THE MODEL AGAINST WHAT WAS BUILT ====
A register records what was decided. These five checks compare it with the application. They are this page's own list.
1. Diagram against the build. List the routes the application serves, the outside hosts it calls, its scheduled jobs and the names of its secrets. Each one should be an element or a flow in Part 1. Add whatever is missing, and ask the six questions of it.
2. Mitigations. Run each acceptance check against the build that will ship. Record pass or fail with the date and the build.
3. Removals. Run the check that shows the feature is gone, and look for anything it left behind, such as a scheduled job or a stored file.
4. Accepted risks and transfers. Confirm each still has an owner in that role, and that the review date has not passed.
5. Assumptions. Check each one and write down how you checked it. A2, for example, is checked by looking for card fields in the studio's own forms and booking API.
==== PART 5. THE KIT (AN ILLUSTRATION) ====
Seven files. threat-register.json is Parts 1 and 2 as data: the lists in Part 1 and the rows in Part 2 were printed from it by a script, so they match. check-register.mjs reports gaps in a register file. seed-gaps.mjs writes a copy of the register with eight gaps in it, so you can watch the checker find them. studio-fixtures.mjs, handler-before.mjs and handler-after.mjs are a very small invented request handler in two versions. acceptance.test.mjs holds five of the register's acceptance criteria as tests.
What this is, exactly:
- The checker checks that a register is complete. It does not check that the threats are the right ones, that a requirement is a good one, or that anything was built.
- The tests run against an invented handler written for this page: plain functions with records held in memory. There is no web server, no database and no payment or email provider behind it. They show a requirement becoming a test. They say nothing about your application.
- The webhook signature in the kit is the lab's own. It is not any real payment provider's scheme. For a real provider, follow that provider's documentation.
The kit imports only node:fs, node:crypto, node:assert/strict and node:test, and installs no packages. It opens no network port.
Written and run on: Node.js 26.0.0 on macOS. Every output in Parts 6 and 7 was copied from that run's captured output by a script. Test timings will differ on your machine.
Setup: create an empty folder, save the seven files below into it under the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 7: threat-register.json
================================================================
{
"system": "Greenware Studio class bookings (invented for this page)",
"reviewedOn": "2026-11-14",
"method": "STRIDE categories used as prompts on each flow that crosses a trust boundary",
"assumptions": [
{
"id": "A1",
"text": "The application, its database, its secrets store and its log run in one hosting account, and only the application can reach the database. So F2, F5, F9, F11, F13 and F14 cross no trust boundary in this model."
},
{
"id": "A2",
"text": "Customers type card details into the payment provider's hosted checkout page. No card number, expiry date or security code is sent to P1."
},
{
"id": "A3",
"text": "Only the studio owner and the lead developer can read the secrets store (D2) in the hosting account."
}
],
"elements": [
{ "id": "E1", "kind": "external entity", "name": "Customer", "notes": "Uses a browser. Has no account." },
{ "id": "E2", "kind": "external entity", "name": "Staff member", "notes": "Uses a browser. Signs in as an instructor or as the studio owner." },
{ "id": "E3", "kind": "external entity", "name": "Payment provider", "notes": "Another company. Hosts the checkout page, takes refund requests and sends payment webhooks." },
{ "id": "E4", "kind": "external entity", "name": "Email provider", "notes": "Another company. Delivers the application's email." },
{ "id": "P1", "kind": "process", "name": "Booking site", "notes": "Public pages and the booking API." },
{ "id": "P2", "kind": "process", "name": "Staff area", "notes": "Class rosters, attendance and refunds." },
{ "id": "P3", "kind": "process", "name": "Payment webhook endpoint", "notes": "Receives the payment provider's webhooks." },
{ "id": "P4", "kind": "process", "name": "Scheduled jobs", "notes": "Run on a timer. Send reminder emails." },
{ "id": "D1", "kind": "data store", "name": "Bookings database", "notes": "Classes, bookings, customers' names, email addresses and phone numbers, staff accounts." },
{ "id": "D2", "kind": "data store", "name": "Secrets store", "notes": "Payment API key, webhook signing secret, email API key, session signing key." },
{ "id": "D3", "kind": "data store", "name": "Application log", "notes": "One entry per event, written by every process." }
],
"trustBoundaries": [
{ "id": "TB1", "name": "Internet edge", "description": "Between anything a browser or another company's server sends and the studio's application." },
{ "id": "TB2", "name": "Staff line", "description": "Between what any visitor may do and what only signed-in staff may do, and inside the staff area between an instructor and the studio owner." },
{ "id": "TB3", "name": "Third-party line", "description": "Between the studio's application and services that other companies run." }
],
"flows": [
{ "id": "F1", "from": ["E1"], "to": ["P1"], "data": "Booking request: class, number of seats, name, email address, phone number.", "crosses": ["TB1"] },
{ "id": "F2", "from": ["P1"], "to": ["D1"], "data": "Read the seats left. Write the unpaid booking.", "crosses": [] },
{ "id": "F3", "from": ["P1"], "to": ["E3"], "data": "Create a checkout session: booking id and amount, sent with the payment API key.", "crosses": ["TB3"] },
{ "id": "F4", "from": ["E3"], "to": ["P3"], "data": "Webhook: payment succeeded, with the booking id, the amount and a signature.", "crosses": ["TB1", "TB3"] },
{ "id": "F5", "from": ["P3"], "to": ["D1"], "data": "Mark the booking paid.", "crosses": [] },
{ "id": "F6", "from": ["P3"], "to": ["E4"], "data": "Confirmation email: first name, class, time and the manage link, sent with the email API key.", "crosses": ["TB3"] },
{ "id": "F7", "from": ["E1"], "to": ["P1"], "data": "Manage-link request: the token from the email, to view, cancel or move one booking.", "crosses": ["TB1"] },
{ "id": "F8", "from": ["E2"], "to": ["P2"], "data": "Staff sign-in, then roster, attendance and refund requests.", "crosses": ["TB1", "TB2"] },
{ "id": "F9", "from": ["P2"], "to": ["D1"], "data": "Read rosters. Write attendance and refunds.", "crosses": [] },
{ "id": "F10", "from": ["P2"], "to": ["E3"], "data": "Refund request: payment id and amount, sent with the payment API key.", "crosses": ["TB3"] },
{ "id": "F11", "from": ["P4"], "to": ["D1"], "data": "Read tomorrow's bookings.", "crosses": [] },
{ "id": "F12", "from": ["P4"], "to": ["E4"], "data": "Reminder email: first name, class and time, sent with the email API key.", "crosses": ["TB3"] },
{ "id": "F13", "from": ["P1", "P2", "P3", "P4"], "to": ["D2"], "data": "Read secrets when the application starts.", "crosses": [] },
{ "id": "F14", "from": ["P1", "P2", "P3", "P4"], "to": ["D3"], "data": "Write log entries.", "crosses": [] },
{ "id": "F15", "from": ["P4"], "to": ["E4"], "data": "Planned and then removed (see T11): a nightly email to the owner with a file of every customer's name, email address and phone number.", "crosses": ["TB3"] }
],
"threats": [
{
"id": "T1",
"appliesTo": ["F1"],
"boundaries": ["TB1"],
"category": "Denial of service",
"threat": "Someone holds every seat in a class with bookings they never pay for, so real customers see the class as full.",
"abuseCase": "A person, or a script, starts bookings for all the seats in a popular class and abandons each one at the payment step, again and again.",
"decision": "mitigate",
"requirement": "An unpaid booking holds its seats for 15 minutes. After that the seats are released and the booking can no longer be paid.",
"owner": "Backend developer",
"acceptance": {
"check": "Start a booking for 2 seats in a class with 8 seats and do not pay. Read the seats left straight away, and again once 16 minutes have passed on the application's clock.",
"pass": "6 seats left, then 8.",
"fail": "Still 6 seats left after 16 minutes."
}
},
{
"id": "T2",
"appliesTo": ["F1"],
"boundaries": ["TB1"],
"category": "Tampering",
"threat": "The amount to charge is taken from the booking request, so a customer can change it before it is sent.",
"abuseCase": "A customer edits the request in the browser and sends an amount of 1 cent for two seats.",
"decision": "mitigate",
"requirement": "The server works out the amount from the class price it holds and the number of seats. An amount sent in the request is ignored.",
"owner": "Backend developer",
"acceptance": {
"check": "Send a booking request for 2 seats in a class priced at 9500 cents a seat, with an amount of 1 cent added to the request.",
"pass": "The booking is stored with 19000 cents due.",
"fail": "The booking is stored with any other amount due."
}
},
{
"id": "T3",
"appliesTo": ["F3", "F10"],
"boundaries": ["TB3"],
"category": "Information disclosure",
"threat": "The payment API key leaks from the repository, a log or a laptop, and whoever holds it can ask the provider for refunds in the studio's name.",
"abuseCase": "Someone finds the key in an old commit or a pasted error message and uses it to send refund requests.",
"decision": "mitigate",
"requirement": "The payment API key is kept only in the hosting account's secrets store (D2), and a secret scan runs on every push and fails the build when it finds a key.",
"owner": "Lead developer",
"acceptance": {
"check": "Push a test branch that contains a made-up string in the provider's key format.",
"pass": "The build fails and names the file.",
"fail": "The build passes."
}
},
{
"id": "T4",
"appliesTo": ["F4"],
"boundaries": ["TB1", "TB3"],
"category": "Spoofing",
"threat": "Anyone on the internet can send the webhook endpoint a message that claims a booking was paid.",
"abuseCase": "A customer starts a booking, skips the payment and posts a made-up payment-succeeded message for their booking id to the webhook address.",
"decision": "mitigate",
"requirement": "The webhook endpoint accepts a message only when its signature, checked with the webhook signing secret over the exact text received, is valid, and only when the amount in the message equals the amount due on the booking. Anything else is refused and changes nothing.",
"owner": "Backend developer",
"acceptance": {
"check": "Post a payment-succeeded message for an unpaid booking with no signature, then with a signature made with the wrong secret.",
"pass": "Both are refused with status 400 and the booking is still unpaid.",
"fail": "Either message is accepted, or the booking is marked paid."
}
},
{
"id": "T5",
"appliesTo": ["F6", "F12"],
"boundaries": ["TB3"],
"category": "Information disclosure",
"threat": "Every email hands customers' details to another company and to whoever can read the inbox, and each extra field sent is one more that can leak.",
"abuseCase": "Someone with access to a customer's inbox, or to the email provider's message log, reads phone numbers and staff notes that the email did not need to carry.",
"decision": "mitigate",
"requirement": "Confirmation and reminder emails carry the customer's first name, the class, its time and, for a confirmation, the manage link. They carry no surname, no phone number and no staff notes.",
"owner": "Backend developer",
"acceptance": {
"check": "In the test environment, capture what the application hands to the email provider for one confirmation and one reminder.",
"pass": "Each message holds only the fields the requirement lists.",
"fail": "Either message holds a surname, a phone number or a staff note."
}
},
{
"id": "T6",
"appliesTo": ["F7"],
"boundaries": ["TB1"],
"category": "Spoofing",
"threat": "The manage link is the only thing that shows who the customer is, so anyone who can guess a token or reuse an old one can act as that customer.",
"abuseCase": "Someone changes characters in a manage link to try other bookings, or uses an old link after the class has run.",
"decision": "mitigate",
"requirement": "A manage token is 32 random bytes from the platform's cryptographic random source, is stored only as a hash, works for one booking and stops working when the class starts. A wrong or expired token gets the same 404 as an address that does not exist.",
"owner": "Backend developer",
"acceptance": {
"check": "Request the manage page with a token changed by one character, and with a real token once the class start time has passed on the application's clock.",
"pass": "Both requests get status 404 and no booking details.",
"fail": "Either request shows or changes a booking."
}
},
{
"id": "T7",
"appliesTo": ["F7"],
"boundaries": ["TB1"],
"category": "Information disclosure",
"threat": "Anyone who is forwarded a confirmation email holds a working manage link.",
"abuseCase": "A customer forwards the confirmation to a friend who is coming along, and the friend, or anyone else that email reaches, cancels or moves the booking.",
"decision": "accept",
"decisionNote": "Customers have no accounts, so the link is the only credential. The manage page shows a first name, the class and its time, and lets the holder cancel or move that one booking. Staff can restore a cancelled booking from the roster. Look at this again if customer accounts are added, and on the review date at the latest.",
"owner": "Studio owner",
"reviewDate": "2027-05-14"
},
{
"id": "T8",
"appliesTo": ["F8"],
"boundaries": ["TB1", "TB2"],
"category": "Spoofing",
"threat": "A staff password that is guessed, phished or reused from another site lets an outsider sign in to the staff area.",
"abuseCase": "Someone tries passwords from a leaked list against the owner's email address on the staff sign-in page.",
"decision": "mitigate",
"requirement": "Staff sign-in needs a password and a second factor.",
"owner": "Lead developer",
"acceptance": {
"check": "Sign in to a staff test account with the right password and no second factor, then request a roster.",
"pass": "The roster request is refused with status 401.",
"fail": "The roster is returned."
}
},
{
"id": "T9",
"appliesTo": ["F8"],
"boundaries": ["TB2"],
"category": "Elevation of privilege",
"threat": "The refund button is hidden from instructors, but the refund request itself is open to any signed-in staff member.",
"abuseCase": "An instructor, or someone using an instructor's session, sends the refund request directly instead of using the screen.",
"decision": "mitigate",
"requirement": "Every staff request checks the signed-in person's role on the server, and a refund needs the owner role. Needing the owner role for a refund follows ASVS 5.0 requirement 8.2.1 (Level 1), which asks that function-level access is restricted to consumers with explicit permissions. Checking the role on the server follows requirement 8.3.1 (Level 1), which asks that authorisation rules are enforced at a trusted service layer and do not rely on controls that an untrusted consumer could manipulate, such as client-side JavaScript.",
"owner": "Backend developer",
"acceptance": {
"check": "Send a refund request for a paid booking from an instructor's session.",
"pass": "Status 403 and no refund recorded.",
"fail": "Any other status, or a refund recorded."
}
},
{
"id": "T10",
"appliesTo": ["F8"],
"boundaries": ["TB2"],
"category": "Repudiation",
"threat": "A refund is issued and nobody can show which staff member issued it.",
"abuseCase": "A staff member refunds a friend's booking from a login the whole studio shares, and later says it was not them.",
"decision": "mitigate",
"requirement": "Each staff member has their own account, and every refund writes a log entry with the staff account, the booking, the amount and the time.",
"owner": "Backend developer",
"acceptance": {
"check": "Issue one refund from the owner's test account, then read the log.",
"pass": "One refund entry, and it names that account, the booking, the amount and a time.",
"fail": "No refund entry, more than one, or an entry with any of the four missing."
}
},
{
"id": "T11",
"appliesTo": ["F15"],
"boundaries": ["TB3"],
"category": "Information disclosure",
"threat": "A nightly email would put every customer's name, email address and phone number in one file, in an inbox and at the email provider.",
"abuseCase": "Someone who gets into the owner's mailbox, or who is sent the file by mistake, has the studio's whole customer list.",
"decision": "remove",
"decisionNote": "The nightly emailed customer export (F15) is taken out of the release. The roster screen in the staff area covers the need it was meant for.",
"requirement": "The application has no export route and no scheduled export job.",
"owner": "Lead developer",
"acceptance": {
"check": "Request the export address from the owner's session, and list the scheduled jobs.",
"pass": "Status 404, and the only scheduled job is the reminder emails.",
"fail": "A file is returned, or an export job is listed."
}
},
{
"id": "T12",
"appliesTo": ["F3"],
"boundaries": ["TB3"],
"category": "Information disclosure",
"threat": "Card details handled by the studio's own application could be read from its requests, its log or its database.",
"abuseCase": "Someone who gets into the application or its log looks for stored card numbers.",
"decision": "transfer",
"decisionNote": "Customers type card details into the payment provider's hosted checkout page (assumption A2), and the provider's agreement with the studio covers storing and processing them. What stays with the studio: the amount it asks the provider to charge (T2), the payment API key (T3) and the webhook endpoint (T4).",
"transferredTo": "Payment provider",
"owner": "Lead developer"
},
{
"id": "T13",
"appliesTo": ["D3"],
"boundaries": [],
"category": "Information disclosure",
"threat": "The application log collects customers' details and working manage tokens, and more people can read the log than can read the database.",
"abuseCase": "Someone with access to the log viewer copies a manage token or a customer's phone number out of a logged request.",
"decision": "mitigate",
"requirement": "A log entry carries the booking id and the name of the event. It never carries a manage token, an email address, a phone number or the text of a request.",
"owner": "Backend developer",
"acceptance": {
"check": "In the test environment, make one booking and open its manage link, then search the log for the test customer's email address, phone number and token.",
"pass": "None of the three is found.",
"fail": "Any of the three is found."
}
}
]
}
================================================================
FILE 2 OF 7: check-register.mjs
================================================================
// check-register.mjs: reads a threat register file and lists the gaps in it.
// It checks that the register is complete: every flow that crosses a trust
// boundary has a threat recorded against it, every threat has a decision,
// every decision has the fields it needs, and every id a flow or a threat
// names is in the diagram. It does not judge whether the threats are the
// right ones or whether a requirement is a good one. Illustration only.
import { readFileSync } from 'node:fs'
const DECISIONS = ['mitigate', 'accept', 'remove', 'transfer']
function hasText(value) {
return typeof value === 'string' && value.trim().length > 0
}
// True for a calendar date written as YYYY-MM-DD, such as 2027-05-14.
function isCalendarDate(value) {
if (!hasText(value)) return false
const date = new Date(value + 'T00:00:00Z')
if (Number.isNaN(date.getTime())) return false
return date.toISOString().slice(0, 10) === value
}
function listIds(items) {
const ids = new Set()
for (const item of items) ids.add(item.id)
return ids
}
// One gap for each id in the list that the diagram does not have.
function findUnknownIds(label, ids, knownIds, kind) {
const gaps = []
for (const id of ids) {
if (!knownIds.has(id)) gaps.push(label + ' names ' + id + ', which is not ' + kind + ' in the diagram.')
}
return gaps
}
function findUnknownReferences(register) {
const elementIds = listIds(register.elements)
const boundaryIds = listIds(register.trustBoundaries)
const elementAndFlowIds = listIds(register.elements.concat(register.flows))
let gaps = []
for (const flow of register.flows) {
gaps = gaps.concat(findUnknownIds(flow.id, flow.from.concat(flow.to), elementIds, 'an element'))
gaps = gaps.concat(findUnknownIds(flow.id, flow.crosses, boundaryIds, 'a trust boundary'))
}
for (const threat of register.threats) {
gaps = gaps.concat(findUnknownIds(threat.id, threat.appliesTo, elementAndFlowIds, 'an element or a flow'))
gaps = gaps.concat(findUnknownIds(threat.id, threat.boundaries, boundaryIds, 'a trust boundary'))
}
return gaps
}
// A flow that crosses a trust boundary needs at least one threat that applies to it.
function findUncoveredFlows(register) {
const coveredIds = new Set()
for (const threat of register.threats) {
for (const id of threat.appliesTo) coveredIds.add(id)
}
const gaps = []
for (const flow of register.flows) {
const crossesBoundary = flow.crosses.length > 0
if (crossesBoundary && !coveredIds.has(flow.id)) {
gaps.push(flow.id + ' crosses ' + flow.crosses.join(' and ') + ' and has no threat recorded against it.')
}
}
return gaps
}
// An acceptance criterion is a check with a pass condition and a fail condition.
function findAcceptanceGaps(threat, label) {
const acceptance = threat.acceptance
if (!acceptance) return [label + ' with no acceptance criterion.']
const gaps = []
if (!hasText(acceptance.check)) gaps.push(label + ' whose acceptance criterion has no check.')
if (!hasText(acceptance.pass)) gaps.push(label + ' whose acceptance criterion has no pass condition.')
if (!hasText(acceptance.fail)) gaps.push(label + ' whose acceptance criterion has no fail condition.')
return gaps
}
// A mitigation and a removal both lead to work that someone builds and someone checks.
function findBuildGaps(threat, label) {
const gaps = []
if (!hasText(threat.requirement)) gaps.push(label + ' with no requirement.')
if (!hasText(threat.owner)) gaps.push(label + ' with no owner.')
return gaps.concat(findAcceptanceGaps(threat, label))
}
function findAcceptedRiskGaps(threat) {
const label = threat.id + ' is an accepted risk'
const gaps = []
if (!hasText(threat.owner)) gaps.push(label + ' with no owner.')
if (!isCalendarDate(threat.reviewDate)) gaps.push(label + ' with no review date.')
return gaps
}
function findTransferGaps(threat) {
const label = threat.id + ' is a transfer'
const gaps = []
if (!hasText(threat.transferredTo)) gaps.push(label + ' that does not name who takes it on.')
if (!hasText(threat.owner)) gaps.push(label + ' with no owner for what stays behind.')
return gaps
}
function findDecisionGaps(threat) {
if (!hasText(threat.decision)) return [threat.id + ' has no decision.']
if (!DECISIONS.includes(threat.decision)) return [threat.id + ' has a decision that is not one of: ' + DECISIONS.join(', ') + '.']
if (threat.decision === 'mitigate') return findBuildGaps(threat, threat.id + ' is a mitigation')
if (threat.decision === 'remove') return findBuildGaps(threat, threat.id + ' is a removal')
if (threat.decision === 'accept') return findAcceptedRiskGaps(threat)
return findTransferGaps(threat)
}
function findGaps(register) {
let gaps = findUnknownReferences(register).concat(findUncoveredFlows(register))
for (const threat of register.threats) gaps = gaps.concat(findDecisionGaps(threat))
return gaps
}
function countDecisions(threats) {
const parts = []
for (const decision of DECISIONS) {
const count = threats.filter((threat) => threat.decision === decision).length
parts.push(count + ' ' + decision)
}
return parts.join(', ')
}
function printSummary(path, register) {
const crossingFlows = register.flows.filter((flow) => flow.crosses.length > 0)
console.log('Register: ' + path)
console.log('System: ' + register.system)
console.log(register.elements.length + ' elements, ' + register.flows.length + ' flows (' + crossingFlows.length +
' cross a trust boundary), ' + register.trustBoundaries.length + ' trust boundaries, ' + register.threats.length + ' threats')
console.log('Decisions: ' + countDecisions(register.threats))
}
function printGaps(gaps) {
if (gaps.length === 0) {
console.log('No gaps found. Every entry is complete. Whether the threats are the right ones is for people to judge.')
return
}
console.log(gaps.length + ' gaps found:')
for (const gap of gaps) console.log(' ' + gap)
}
function main() {
const path = process.argv[2]
if (!path) {
console.log('Usage: node check-register.mjs threat-register.json')
process.exitCode = 2
return
}
const register = JSON.parse(readFileSync(path, 'utf8'))
const gaps = findGaps(register)
printSummary(path, register)
printGaps(gaps)
// Exit code 1 when there is at least one gap, so a pipeline step can stop on it.
process.exitCode = gaps.length === 0 ? 0 : 1
}
main()
================================================================
FILE 3 OF 7: seed-gaps.mjs
================================================================
// seed-gaps.mjs: copies threat-register.json to threat-register-with-gaps.json
// with eight changes made on purpose, so the checker has gaps to report.
// It prints each change. It does not change threat-register.json.
import { readFileSync, writeFileSync } from 'node:fs'
const register = JSON.parse(readFileSync('threat-register.json', 'utf8'))
function findThreat(id) {
return register.threats.find((threat) => threat.id === id)
}
function note(change) {
console.log(' ' + change)
}
console.log('Seeding gaps into a copy of threat-register.json:')
register.threats = register.threats.filter((threat) => threat.id !== 'T4')
note('Took out threat T4, the only threat recorded against flow F4.')
delete findThreat('T2').decision
note('Took the decision out of T2.')
delete findThreat('T9').requirement
note('Took the requirement out of T9.')
delete findThreat('T10').owner
note('Took the owner out of T10.')
delete findThreat('T13').acceptance.fail
note('Took the fail condition out of the acceptance criterion of T13.')
delete findThreat('T7').owner
note('Took the owner out of T7, the accepted risk.')
delete findThreat('T7').reviewDate
note('Took the review date out of T7.')
findThreat('T12').appliesTo = ['F30']
note('Pointed T12 at F30, a flow the diagram does not have.')
writeFileSync('threat-register-with-gaps.json', JSON.stringify(register, null, 2))
console.log('Wrote threat-register-with-gaps.json')
================================================================
FILE 4 OF 7: studio-fixtures.mjs
================================================================
// studio-fixtures.mjs: the invented studio's test data and small helpers,
// shared by both versions of the handler and by the tests. Everything here is
// made up for this page. The signature below is the lab's own. It is not any
// real payment provider's scheme.
import { createHmac } from 'node:crypto'
export const CLASS_PRICE_CENTS = 9500
export const WEBHOOK_SECRET = 'lab-webhook-secret'
export const WEBHOOK_SIGNATURE_HEADER = 'x-lab-signature'
// Two invented staff sessions, with the account and the role each one carries.
export const STAFF_SESSIONS = {
'session-owner-1': { account: 'owner-1', role: 'owner' },
'session-instructor-1': { account: 'instructor-1', role: 'instructor' },
}
// The lab's signature: a hex HMAC-SHA-256 of the exact message text.
export function signWebhook(messageText, secret) {
return createHmac('sha256', secret).update(messageText).digest('hex')
}
// Records are held in memory. Each call gives a new, empty set.
export function createStore() {
return { bookings: [], refunds: [], log: [], nextBookingNumber: 1 }
}
export function findBooking(store, bookingId) {
return store.bookings.find((booking) => booking.id === bookingId) || null
}
export function respond(status, body) {
return { status: status, body: body }
}
================================================================
FILE 5 OF 7: handler-before.mjs
================================================================
// handler-before.mjs: the invented studio's request handler as first written,
// before the register's requirements were built. It does not meet the
// requirements for T2, T4, T9, T10 and T11, and a comment marks the line
// behind each one.
import { CLASS_PRICE_CENTS, STAFF_SESSIONS, createStore, findBooking, respond } from './studio-fixtures.mjs'
// T11: the nightly customer export is still scheduled.
const SCHEDULED_JOBS = ['reminder emails', 'nightly customer export']
function createBooking(store, request) {
const seats = request.body.seats
// T2: when the request sends an amount, that amount is stored as the amount due.
const sentAmount = request.body.amountCents
const amountDueCents = sentAmount === undefined ? seats * CLASS_PRICE_CENTS : sentAmount
const booking = {
id: 'b' + store.nextBookingNumber,
seats: seats,
amountDueCents: amountDueCents,
state: 'unpaid',
customerName: request.body.name,
customerEmail: request.body.email,
}
store.nextBookingNumber += 1
store.bookings.push(booking)
return respond(201, { id: booking.id, amountDueCents: booking.amountDueCents, state: booking.state })
}
function receivePaymentWebhook(store, request) {
// T4: the message is read as sent. No signature is checked and no amount is compared.
const message = JSON.parse(request.rawBody)
const booking = findBooking(store, message.bookingId)
if (!booking) return respond(404, { error: 'no such booking' })
booking.state = 'paid'
return respond(200, { received: true })
}
function refundBooking(store, request) {
const staff = STAFF_SESSIONS[request.session]
if (!staff) return respond(401, { error: 'not signed in' })
// T9: any signed-in staff member gets this far. The role is not checked.
const booking = findBooking(store, request.body.bookingId)
if (!booking || booking.state !== 'paid') return respond(409, { error: 'nothing to refund' })
booking.state = 'refunded'
store.refunds.push({ bookingId: booking.id, amountCents: booking.amountDueCents })
// T10: the log entry does not say which account issued the refund, or when.
store.log.push({ event: 'refund issued', bookingId: booking.id })
return respond(200, { refundedCents: booking.amountDueCents })
}
// T11: an export route that returns every customer's name and email address.
function exportCustomers(store, request) {
const staff = STAFF_SESSIONS[request.session]
if (!staff) return respond(401, { error: 'not signed in' })
const rows = store.bookings.map((booking) => booking.customerName + ',' + booking.customerEmail)
return respond(200, { rows: rows })
}
const ROUTES = {
'POST /bookings': createBooking,
'POST /webhooks/payment': receivePaymentWebhook,
'POST /staff/refunds': refundBooking,
'GET /staff/export': exportCustomers,
}
export function createHandler() {
const store = createStore()
function handle(request) {
const route = ROUTES[request.method + ' ' + request.path]
if (!route) return respond(404, { error: 'not found' })
return route(store, request)
}
return { store: store, scheduledJobs: SCHEDULED_JOBS, handle: handle }
}
================================================================
FILE 6 OF 7: handler-after.mjs
================================================================
// handler-after.mjs: the same handler once the register's requirements for
// T2, T4, T9, T10 and T11 have been built. A comment marks the line that
// meets each one.
import { timingSafeEqual } from 'node:crypto'
import {
CLASS_PRICE_CENTS,
STAFF_SESSIONS,
WEBHOOK_SECRET,
WEBHOOK_SIGNATURE_HEADER,
createStore,
findBooking,
respond,
signWebhook,
} from './studio-fixtures.mjs'
// T11: the nightly customer export is no longer scheduled.
const SCHEDULED_JOBS = ['reminder emails']
function createBooking(store, request) {
const seats = request.body.seats
// T2: the amount due comes from the class price and the seats. An amount in the request is not read.
const amountDueCents = seats * CLASS_PRICE_CENTS
const booking = {
id: 'b' + store.nextBookingNumber,
seats: seats,
amountDueCents: amountDueCents,
state: 'unpaid',
customerName: request.body.name,
customerEmail: request.body.email,
}
store.nextBookingNumber += 1
store.bookings.push(booking)
return respond(201, { id: booking.id, amountDueCents: booking.amountDueCents, state: booking.state })
}
// True when the signature header equals the lab's signature of the exact text received.
function isWebhookSignatureValid(request) {
const sentSignature = request.headers[WEBHOOK_SIGNATURE_HEADER]
if (typeof sentSignature !== 'string') return false
const expectedSignature = signWebhook(request.rawBody, WEBHOOK_SECRET)
const sent = Buffer.from(sentSignature)
const expected = Buffer.from(expectedSignature)
if (sent.length !== expected.length) return false
return timingSafeEqual(sent, expected)
}
function receivePaymentWebhook(store, request) {
// T4: the signature is checked before the message is read.
if (!isWebhookSignatureValid(request)) return respond(400, { error: 'signature not valid' })
const message = JSON.parse(request.rawBody)
const booking = findBooking(store, message.bookingId)
if (!booking) return respond(404, { error: 'no such booking' })
// T4: the amount in the message has to equal the amount due on the booking.
if (message.amountCents !== booking.amountDueCents) return respond(400, { error: 'amount does not match the booking' })
booking.state = 'paid'
return respond(200, { received: true })
}
function refundBooking(store, request) {
const staff = STAFF_SESSIONS[request.session]
if (!staff) return respond(401, { error: 'not signed in' })
// T9: a refund needs the owner role.
if (staff.role !== 'owner') return respond(403, { error: 'a refund needs the owner role' })
const booking = findBooking(store, request.body.bookingId)
if (!booking || booking.state !== 'paid') return respond(409, { error: 'nothing to refund' })
booking.state = 'refunded'
store.refunds.push({ bookingId: booking.id, amountCents: booking.amountDueCents })
// T10: the log entry names the staff account, the booking, the amount and the time.
store.log.push({
event: 'refund issued',
account: staff.account,
bookingId: booking.id,
amountCents: booking.amountDueCents,
at: new Date().toISOString(),
})
return respond(200, { refundedCents: booking.amountDueCents })
}
// T11: there is no export route, so a request for one gets the 404 below.
const ROUTES = {
'POST /bookings': createBooking,
'POST /webhooks/payment': receivePaymentWebhook,
'POST /staff/refunds': refundBooking,
}
export function createHandler() {
const store = createStore()
function handle(request) {
const route = ROUTES[request.method + ' ' + request.path]
if (!route) return respond(404, { error: 'not found' })
return route(store, request)
}
return { store: store, scheduledJobs: SCHEDULED_JOBS, handle: handle }
}
================================================================
FILE 7 OF 7: acceptance.test.mjs
================================================================
// acceptance.test.mjs: five of the register's acceptance criteria (T2, T4, T9,
// T10 and T11) written as tests for the Node.js test runner, and run against
// one version of the invented handler. Name the version on the command line:
// before or after. With no name, the after version is tested. Each test is
// named with the threat id and the pass condition read from the register.
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
import { createHandler as createHandlerAfter } from './handler-after.mjs'
import { createHandler as createHandlerBefore } from './handler-before.mjs'
import { CLASS_PRICE_CENTS, WEBHOOK_SECRET, WEBHOOK_SIGNATURE_HEADER, signWebhook } from './studio-fixtures.mjs'
const HANDLERS = { before: createHandlerBefore, after: createHandlerAfter }
const version = process.argv[2] || 'after'
const createHandler = HANDLERS[version]
if (!createHandler) throw new Error('Name a version: before or after')
const register = JSON.parse(readFileSync('threat-register.json', 'utf8'))
function nameFor(threatId) {
const threat = register.threats.find((item) => item.id === threatId)
return version + ': ' + threatId + ' passes when: ' + threat.acceptance.pass
}
function bookTwoSeats(studio, extraFields) {
const body = Object.assign({ seats: 2, name: 'Test Customer', email: 'test.customer@studio.example' }, extraFields)
const response = studio.handle({ method: 'POST', path: '/bookings', body: body })
assert.equal(response.status, 201)
return studio.store.bookings[0]
}
function paymentMessageFor(booking) {
return JSON.stringify({ event: 'payment succeeded', bookingId: booking.id, amountCents: booking.amountDueCents })
}
function postWebhook(studio, messageText, signature) {
const headers = {}
if (signature) headers[WEBHOOK_SIGNATURE_HEADER] = signature
return studio.handle({ method: 'POST', path: '/webhooks/payment', headers: headers, rawBody: messageText })
}
// Books two seats and pays for them with a correctly signed message, which both versions accept.
function bookAndPay(studio) {
const booking = bookTwoSeats(studio, {})
const messageText = paymentMessageFor(booking)
const response = postWebhook(studio, messageText, signWebhook(messageText, WEBHOOK_SECRET))
assert.equal(response.status, 200)
assert.equal(booking.state, 'paid')
return booking
}
function requestRefund(studio, session, booking) {
return studio.handle({ method: 'POST', path: '/staff/refunds', session: session, body: { bookingId: booking.id } })
}
test(nameFor('T2'), () => {
const studio = createHandler()
const booking = bookTwoSeats(studio, { amountCents: 1 })
assert.equal(booking.amountDueCents, 2 * CLASS_PRICE_CENTS)
})
test(nameFor('T4'), () => {
const studio = createHandler()
const booking = bookTwoSeats(studio, {})
const messageText = paymentMessageFor(booking)
const unsigned = postWebhook(studio, messageText, null)
const wronglySigned = postWebhook(studio, messageText, signWebhook(messageText, 'a secret the studio does not use'))
assert.equal(unsigned.status, 400)
assert.equal(wronglySigned.status, 400)
assert.equal(booking.state, 'unpaid')
})
test(nameFor('T9'), () => {
const studio = createHandler()
const booking = bookAndPay(studio)
const response = requestRefund(studio, 'session-instructor-1', booking)
assert.equal(response.status, 403)
assert.equal(studio.store.refunds.length, 0)
})
test(nameFor('T10'), () => {
const studio = createHandler()
const booking = bookAndPay(studio)
const response = requestRefund(studio, 'session-owner-1', booking)
assert.equal(response.status, 200)
const refundEntries = studio.store.log.filter((entry) => entry.event === 'refund issued')
assert.equal(refundEntries.length, 1)
assert.equal(refundEntries[0].account, 'owner-1')
assert.equal(refundEntries[0].bookingId, booking.id)
assert.equal(refundEntries[0].amountCents, booking.amountDueCents)
assert.equal(typeof refundEntries[0].at, 'string')
})
test(nameFor('T11'), () => {
const studio = createHandler()
const response = studio.handle({ method: 'GET', path: '/staff/export', session: 'session-owner-1' })
assert.equal(response.status, 404)
assert.deepEqual(studio.scheduledJobs, ['reminder emails'])
})
==== PART 6. RUNNING THE CHECKER ====
Command: node check-register.mjs threat-register.json
Register: threat-register.json
System: Greenware Studio class bookings (invented for this page)
11 elements, 15 flows (9 cross a trust boundary), 3 trust boundaries, 13 threats
Decisions: 10 mitigate, 1 accept, 1 remove, 1 transfer
No gaps found. Every entry is complete. Whether the threats are the right ones is for people to judge.
Command: node seed-gaps.mjs
Seeding gaps into a copy of threat-register.json:
Took out threat T4, the only threat recorded against flow F4.
Took the decision out of T2.
Took the requirement out of T9.
Took the owner out of T10.
Took the fail condition out of the acceptance criterion of T13.
Took the owner out of T7, the accepted risk.
Took the review date out of T7.
Pointed T12 at F30, a flow the diagram does not have.
Wrote threat-register-with-gaps.json
Command: node check-register.mjs threat-register-with-gaps.json
Register: threat-register-with-gaps.json
System: Greenware Studio class bookings (invented for this page)
11 elements, 15 flows (9 cross a trust boundary), 3 trust boundaries, 12 threats
Decisions: 8 mitigate, 1 accept, 1 remove, 1 transfer
8 gaps found:
T12 names F30, which is not an element or a flow in the diagram.
F4 crosses TB1 and TB3 and has no threat recorded against it.
T2 has no decision.
T7 is an accepted risk with no owner.
T7 is an accepted risk with no review date.
T9 is a mitigation with no requirement.
T10 is a mitigation with no owner.
T13 is a mitigation whose acceptance criterion has no fail condition.
Reading the output
The first four lines name the file and count what is in it. The gapped copy counts 12 threats because T4 was taken out, and its decision counts add up to 11 because T2 no longer has a decision.
Each gap is one line that starts with the id of the flow or threat to fix.
T7 appears twice because an accepted risk needs both an owner and a review date, and the copy has neither.
T12 names F30 because of the seeded change. F3, the flow T12 applied to before, is not reported as uncovered, because T3 still applies to it.
==== PART 7. ACCEPTANCE CRITERIA AS TESTS ====
Each test is named with the threat's id and the pass condition read from the register, so a failing line points at a row in Part 2.
Command: node acceptance.test.mjs before
✖ before: T2 passes when: The booking is stored with 19000 cents due. (1.702875ms)
✖ before: T4 passes when: Both are refused with status 400 and the booking is still unpaid. (0.504916ms)
✖ before: T9 passes when: Status 403 and no refund recorded. (0.198042ms)
✖ before: T10 passes when: One refund entry, and it names that account, the booking, the amount and a time. (0.239583ms)
✖ before: T11 passes when: Status 404, and the only scheduled job is the reminder emails. (0.118792ms)
ℹ tests 5
ℹ suites 0
ℹ pass 0
ℹ fail 5
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.197958
✖ failing tests:
test at acceptance.test.mjs:56:1
✖ before: T2 passes when: The booking is stored with 19000 cents due. (1.702875ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
1 !== 19000
(cut here: one line that showed a local file path)
at Test.runInAsyncScope (node:async_hooks:226:14)
at Test.run (node:internal/test_runner/test:1201:25)
at Test.start (node:internal/test_runner/test:1096:17)
at startSubtestAfterBootstrap (node:internal/test_runner/harness:385:17) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 1,
expected: 19000,
operator: 'strictEqual',
diff: 'simple'
}
test at acceptance.test.mjs:62:1
✖ before: T4 passes when: Both are refused with status 400 and the booking is still unpaid. (0.504916ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 400
(cut here: one line that showed a local file path)
at Test.runInAsyncScope (node:async_hooks:226:14)
at Test.run (node:internal/test_runner/test:1201:25)
at Test.processPendingSubtests (node:internal/test_runner/test:831:18)
at Test.postRun (node:internal/test_runner/test:1330:19)
at Test.run (node:internal/test_runner/test:1258:12)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:385:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 400,
operator: 'strictEqual',
diff: 'simple'
}
test at acceptance.test.mjs:73:1
✖ before: T9 passes when: Status 403 and no refund recorded. (0.198042ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 403
(cut here: one line that showed a local file path)
at Test.runInAsyncScope (node:async_hooks:226:14)
at Test.run (node:internal/test_runner/test:1201:25)
at Test.processPendingSubtests (node:internal/test_runner/test:831:18)
at Test.postRun (node:internal/test_runner/test:1330:19)
at Test.run (node:internal/test_runner/test:1258:12)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 403,
operator: 'strictEqual',
diff: 'simple'
}
test at acceptance.test.mjs:81:1
✖ before: T10 passes when: One refund entry, and it names that account, the booking, the amount and a time. (0.239583ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ undefined
- 'owner-1'
(cut here: one line that showed a local file path)
at Test.runInAsyncScope (node:async_hooks:226:14)
at Test.run (node:internal/test_runner/test:1201:25)
at Test.processPendingSubtests (node:internal/test_runner/test:831:18)
at Test.postRun (node:internal/test_runner/test:1330:19)
at Test.run (node:internal/test_runner/test:1258:12)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: undefined,
expected: 'owner-1',
operator: 'strictEqual',
diff: 'simple'
}
test at acceptance.test.mjs:94:1
✖ before: T11 passes when: Status 404, and the only scheduled job is the reminder emails. (0.118792ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 404
(cut here: one line that showed a local file path)
at Test.runInAsyncScope (node:async_hooks:226:14)
at Test.run (node:internal/test_runner/test:1201:25)
at Test.processPendingSubtests (node:internal/test_runner/test:831:18)
at Test.postRun (node:internal/test_runner/test:1330:19)
at Test.run (node:internal/test_runner/test:1258:12)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 404,
operator: 'strictEqual',
diff: 'simple'
}
Command: node acceptance.test.mjs after
✔ after: T2 passes when: The booking is stored with 19000 cents due. (0.843709ms)
✔ after: T4 passes when: Both are refused with status 400 and the booking is still unpaid. (0.418875ms)
✔ after: T9 passes when: Status 403 and no refund recorded. (0.181083ms)
✔ after: T10 passes when: One refund entry, and it names that account, the booking, the amount and a time. (1.110625ms)
✔ after: T11 passes when: Status 404, and the only scheduled job is the reminder emails. (0.957667ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.203583
What the two runs show
The before version fails all five tests. Each failure prints the value the test saw and the value the register's pass condition needs: 1 cent due where 19000 was needed (T2), status 200 where 400 was needed (T4), status 200 where 403 was needed (T9), a refund entry with no account where owner-1 was needed (T10), and status 200 where 404 was needed (T11).
The after version passes all five.
In the failing output, five lines that showed a local file path were cut, one in each failure, and each cut is marked. Nothing else was changed.
Exit codes, as the shell reported them after each command. The last command, node --test, was run in the same folder: it found acceptance.test.mjs by its name and, with no version named, tested the after version.
node check-register.mjs threat-register.json: exit code 0
node seed-gaps.mjs: exit code 0
node check-register.mjs threat-register-with-gaps.json: exit code 1
node acceptance.test.mjs before: exit code 1
node acceptance.test.mjs after: exit code 0
node --test: exit code 0
==== PART 8. USING IT ON YOUR OWN FEATURE ====
1. Copy threat-register.json and replace the elements, flows, trust boundaries and assumptions with your own. Keep the ids short and never reuse one.
2. For each flow that crosses a boundary, ask the six questions and record the threats worth a decision.
3. Give every threat a decision, and fill in what that decision needs. Run check-register.mjs until it reports no gaps.
4. Keep the register file in the repository beside the code it describes, and change it in the same pull request as the feature.
5. Run check-register.mjs as a step in your pipeline. It exits with code 1 when it finds a gap, so a change that adds a boundary-crossing flow to the file with no threat recorded against it fails the step.
6. Write each acceptance criterion you can as a test against your own code, named with the threat's id, and run those tests on every build. Leave the rest as written checks, and record who ran each one, on which build, and what they saw.
7. Work through Part 4 before each release that changed the diagram.What threat modelling is
Threat modelling is something a team does before or while it builds a feature.
A few people draw what they are building: who and what talks to what, which data moves, and where trust changes. They ask what can go wrong at each of those points, decide what to do about each answer, and write every decision down with an owner, and each thing they will build or remove as a requirement with a test. Later they check the drawing and the decisions against what was actually built.
The Threat Modelling Manifesto, published by a working group of people who practise and teach the subject, defines it as analysing representations of a system to highlight concerns about security and privacy characteristics. It says that at the highest levels, when we threat model, we ask four key questions: "What are we working on?", "What can go wrong?", "What are we going to do about it?" and "Did we do a good enough job?" The Manifesto says of itself that it contains ideas, but is not a how-to, and is methodology-agnostic.
OWASP's cheat sheet on threat modelling describes it, in the context of application security, as a structured, repeatable process used to gain actionable insights into the security characteristics of a particular system: modelling the system from a security perspective, identifying applicable threats based on that model, and determining responses to those threats.
It builds on the Manifesto's four questions and breaks the work into four basic steps: application decomposition, threat identification and ranking, mitigations, and review and validation. It also says there is no universally accepted industry standard for the process, and no "right" answer for every use case.
The Manifesto says the output of the threat model, which it calls threats, informs decisions that you might make in subsequent design, development, testing and post-deployment phases. On this page that output takes three forms: a diagram, a register with a decision against every threat, and the requirements and tests those decisions lead to.
A note on spelling. The Manifesto, OWASP, Microsoft and NIST write the term the American way, with one l, including in the titles of their documents cited here. This page uses the Australian spelling throughout, including where it reports their wording.
When a small team should do it, and how much
Early, and more than once.
OWASP's cheat sheet says threat modelling is ideally performed early in the software development lifecycle, such as during the design phase, and that it is not something that is performed once and never again. NIST IR 8397, NIST's guidelines on minimum standards for developer verification of software, recommends using threat modelling early in order to identify design-level security issues and to focus verification.
It says threat modelling should be done multiple times during development, especially when developing new capabilities, to capture new threats and improve modelling.
On the parts that matter, and without ceremony. One of the nine ways OWASP's Top 10:2025 lists to prevent insecure design (A06) is to use threat modelling for critical parts of the application such as authentication, access control, business logic and key flows.
A06 also says threat modelling should be integrated into refinement sessions or similar activities, looking for changes in data flows and access control or other security controls. OWASP's Software Assurance Maturity Model (SAMM) describes the first maturity level of its threat modelling stream as threat modelling performed ad hoc for high-risk applications, using simple threat checklists such as STRIDE.
At that level it says to avoid lengthy workshops and overly detailed lists of low-relevance threats, and, if you add new functionality to an existing application, to look only into the newly added functions instead of trying to cover the entire scope.
It adds that your most important tool to start threat modelling is a whiteboard, smartboard or a piece of paper.
With more than one point of view. SAMM calls threat modelling a team exercise, including product owners, architects, security champions and security testers. Among the patterns the Manifesto says benefit threat modelling is varied viewpoints: assemble a diverse team with appropriate subject matter experts and cross-functional collaboration.
Among the anti-patterns it says inhibit threat modelling is the hero threat modeller: threat modelling does not depend on one's innate ability or unique mindset, and everyone can and should do it.
For a small team that builds its own application, this page's advice is to model a feature when it changes the drawing, not on a calendar. That means a new way in (a route, a webhook, an upload), a new kind of data, a new outside service, a new role, or a change to who may do what.
Bring three points of view, even if two people hold them between them: someone who knows what the business wants the feature to do, someone who will build it, and someone who will test or run it. A change to wording or styling needs no session.
What goes on the diagram
The first question, what are we working on, is answered with a drawing.
OWASP's cheat sheet says that although different techniques may be used in this first step, data flow diagrams are arguably the most common approach. It says to create them using a diagramming tool or a whiteboard, and to save them in a form the team can update.
However the model is produced, the cheat sheet says it is important that it provides a clear view of trust boundaries, data flows, data stores, processes and the external entities which may interact with the system, and that these often represent possible attack points.
Microsoft's training unit on data-flow diagram elements defines the five elements, each with an example:
- Process: a task that receives, modifies or redirects input to output. The example is a web service.
- Data store: permanent and temporary data storage. The examples are a web cache and Azure DB.
- External entity: a task, entity or data store outside of your direct control. The examples are users and third-party APIs.
- Data flow: data movement between processes, data stores and external entities. The examples are connection strings and payloads.
- Trust boundary: trust zone changes as data flows through the system. The example is users connecting to a secured corporate network over the internet.
A diagram you can keep beside the code
A photo of a whiteboard is enough to start. In the example on Microsoft's getting-started page for its threat modelling tool, the human user is drawn as a square, the web server as a circle and the database as two parallel lines, with trust boundaries shown as red dotted lines.
The worked example on this page writes the same information as a numbered list instead, so it can be copied, kept in the repository and changed in a pull request: external entities E1 to E4, processes P1 to P4, data stores D1 to D3, data flows F1 to F15, and trust boundaries TB1 to TB3 with the flows that cross each one.
For each flow, write what moves and what proves who sent it. "Booking id and amount, sent with the payment API key" says more than "calls the payment provider". Number the flows, and keep a flow you decided to remove on the list with a note that says so, because the next person to propose it should find the reason.
Write down what the drawing assumes as well. The worked example records three assumptions, such as "customers type card details into the payment provider's hosted checkout page", and each one is something a person can go and check.
A data flow diagram is not the only way in. The cheat sheet says another approach could be the brainstorming technique, and that the technique is particularly useful when less technical individuals participate in the session.
Why trust boundaries are where to look
A trust boundary is a line where the receiving side should stop taking the sending side's word for anything. Microsoft's training unit on the trust boundary element says trust boundaries are used to describe data flow as it crosses different trust zone levels, and its examples include firewalls, connections to third-party services and parts of your system only available to administrators.
It says areas with changing trust zones are the most targeted by attackers and should be carefully designed. Microsoft's getting-started page says trust boundaries show where different entities are in control.
The worked example has three. The internet edge sits between anything a browser or another company's server sends and the studio's application. The staff line sits between what any visitor may do and what only signed-in staff may do, and inside the staff area between an instructor and the studio owner.
The third-party line sits between the application and the services other companies run for it. Nine of its fifteen flows cross at least one of the three, and the register records at least one threat against each of the nine.
Boundaries are where to start, not where threats end. One threat in the worked register, a log that collects customers' details, crosses no boundary at all. OWASP's A06 names CWE-501, Trust Boundary Violation, among the notable weaknesses in the insecure design category.
Asking what can go wrong without a specialist in the room
The second question goes better with a list of prompts than with a blank page.
OWASP's cheat sheet describes STRIDE as a mature and popular threat modelling technique and mnemonic originally developed by Microsoft employees. It says STRIDE groups threats into one of six general prompts, and that engineers are encouraged to systematically consider how these general threats may materialise within the context of the specific system being evaluated.
Microsoft's getting-started page gives the idea behind it: software comes under a predictable set of threats, which can be found using these six categories.
Microsoft's documentation for its threat modelling tool defines the six categories. OWASP's cheat sheet says each STRIDE threat may be considered a violation of a desirable security attribute, and pairs each category with one. Both are given below. The question after each is this page's own wording, to ask of every flow that crosses a trust boundary.
- Spoofing. Microsoft: illegally accessing and then using another user's authentication information, such as username and password. OWASP: violates authentication. Ask: who or what could pretend to be the sender of this flow?
- Tampering. Microsoft: the malicious modification of data, with examples that include unauthorised changes made to persistent data, such as that held in a database, and the alteration of data as it flows between two computers over an open network, such as the internet. OWASP: violates integrity. Ask: what could be changed before it was sent, or on the way?
- Repudiation. Microsoft: associated with users who deny performing an action without other parties having any way to prove otherwise. OWASP: violates accounting. Ask: if someone says they did not do this, what would show that they did?
- Information disclosure. Microsoft: the exposure of information to individuals who are not supposed to have access to it. OWASP: violates confidentiality. Ask: who could read this that should not, on the way or where it rests?
- Denial of service. Microsoft: attacks that deny service to valid users, for example by making a web server temporarily unavailable or unusable. OWASP: violates availability. Ask: how could someone stop real customers using this?
- Elevation of privilege. Microsoft: an unprivileged user gains privileged access and thereby has sufficient access to compromise or destroy the entire system. OWASP, which writes it as elevation of privileges: violates authorisation. Ask: how could someone do what only a more trusted role may do?
Using the prompts on one flow
Take the payment webhook in the worked example, where the payment provider tells the application that a booking was paid. Spoofing: could anyone else send that message? Yes, because the address is on the internet, and that became threat T4. Tampering: could the amount in the message differ from the amount due on the booking?
The requirement written for T4 covers that as well. Repudiation, information disclosure, denial of service and elevation of privilege were each asked of this flow and produced nothing this page judged worth a row.
Leaving those out follows SAMM's advice to avoid overly detailed lists of low-relevance threats. The cheat sheet says to brainstorm threats with the team and record which components, data flows or trust boundaries they affect. That is the first thing each row of this page's register records.
Microsoft's definition of elevation of privilege is written at the scale of a whole system. The worked register uses the same prompt at a smaller scale, for an instructor reaching a function meant for the studio owner. That reading is this page's own.
Ranking, other techniques and the limits of a checklist
The cheat sheet says that after possible threats have been identified, people will frequently rank them. It says that in theory ranking should be based on the mathematical product of a threat's likelihood and its impact, and that both can be challenging to calculate and ignore the work to fix a problem.
The worked register does not score its thirteen threats. Each one gets a decision, and the decision is what is tracked.
STRIDE is one technique among several. The cheat sheet says to start with STRIDE for a technical design and to select another technique when the scope requires a different view. Its table suggests attack trees for a high-value attacker goal or multi-step attack, misuse or abuse cases for abuse of a valid workflow or business rule, LINDDUN for privacy properties and harms, PASTA for application threats with business impact, OCTAVE for organisation-wide risk to critical assets, and VAST for application and operational threats across many teams. It also says not to add techniques only to make the model appear comprehensive.
Prompts do not replace knowledge. The cheat sheet says many developers lack sufficient knowledge and experience in the field of security, and that in many cases the solution lies in inviting members of the security teams to threat modelling sessions.
A small team with no security team can still ask the six questions. It should expect to miss things a specialist would see, which is one reason the model is checked again after the build.
What an abuse case is, and how it differs from a use case
A use case says what someone is meant to do with a feature: a customer books two seats and pays for them.
An abuse case says what someone might do with the same feature that nobody meant: a customer books two seats, skips the payment and tells the application it was paid. OWASP SAMM, in its misuse and abuse testing stream, says misuse and abuse cases describe unintended and malicious use scenarios of the application, describing how an attacker could do this. It gives using a password reset flow to enumerate accounts as an example of abuse of functionality.
Other OWASP documents lean on the same idea. The cheat sheet suggests misuse or abuse cases for abuse of a valid workflow or business rule, and describes using them to explore actions performed out of order, repeatedly, concurrently or for an unintended outcome. A06 says to compile use-cases and misuse-cases for each tier of your application.
The WSTG v4.2 introduction to business logic testing says tests for business logic flaws require that security professionals think a bit differently, develop abuse and misuse cases and use many of the testing techniques embraced by functional testers. Appendix D of ASVS 5.0 lists, among items that were previously in ASVS, verifying that all user stories and features contain functional security constraints, with the example "As a user, I should be able to view and edit my profile. I should not be able to view or edit anyone else's profile".
In the register on this page, the threat and the abuse case are separate columns because they do different jobs. The threat is the general statement: anyone on the internet can send the webhook endpoint a message that claims a booking was paid.
The abuse case is one person doing one thing: a customer starts a booking, skips the payment and posts a made-up payment-succeeded message for their booking id to the webhook address.
Write it with a person, an action and a goal, in plain words, at the level a tester needs to write the check. It does not need to be an attack recipe.
One of SAMM's quality criteria for the second maturity level of that stream is that you capture identified weaknesses as security requirements. The next two sections do that.
Deciding what to do about each threat
The third question ends in a decision.
The cheat sheet says each threat identified must have a response, and gives four, which it credits to Adam Shostack:
- Mitigate:take action to reduce the likelihood that the threat will materialise.
- Eliminate:simply remove the feature or component that is causing the threat.
- Transfer:allocate contractual or financial responsibility to another party. The cheat sheet adds that risk transfer does not itself reduce the likelihood or harmful consequences of an event, and says to document who owns the remaining controls and residual risk.
- Accept:do not mitigate, eliminate or transfer the risk because none of the above options are acceptable given business requirements or constraints.
The four decisions in the worked register
The register on this page uses the same four and calls the second one remove. Ten of its thirteen threats are mitigated. One is removed: a planned nightly email carrying a file of every customer's details was taken out of the release, because the roster screen already covered the need.
One is transferred: customers type card details into the payment provider's hosted page, and the row names the lead developer as the owner of what stays with the studio.
One is accepted: anyone who is forwarded a confirmation email holds a working link for managing that booking, and the studio owner accepts that until a named review date.
Removing a feature is a real option, and OWASP gives a case of it. A06's first example scenario describes a credential recovery workflow that might include "questions and answers", and says such functionality should be removed and replaced with a more secure design.
An accepted risk has a name and a date
An accepted risk with no owner and no date is a threat nobody decided on. NIST SP 800-218 gives, as one of its notional examples for the task of tracking security requirements, risks and design decisions, periodically re-evaluating all approved exceptions to the security requirements and implementing changes as needed.
In the worked register, the accepted risk carries the role that accepted it, the reason, what would reopen it and a review date, and the checker reports an accepted risk that lacks an owner or a date.
This page's advice is that the role accepting a risk should be the one that answers for the loss. In a small business that is its owner, not the developer who would otherwise have to fix it.
How a decision becomes a requirement with an owner and a test
A decision to mitigate is not finished until someone can check it.
The cheat sheet says to document each threat's response and turn agreed mitigations into actionable security requirements, and to record how the team will implement each mitigation and why it accepts any remaining risk. Its review step asks whether the agreed mitigations can be tested, and whether success or failure of the requirements and recommendations from the threat model can be measured.
A06 says to write unit and integration tests to validate that all critical flows are resistant to the threat model.
Three things make a decision checkable. The requirement says what has to be true in words someone can observe. "The webhook is safe" cannot be tested. "The webhook endpoint accepts a message only when its signature is valid and the amount in the message equals the amount due on the booking" can.
The owner is a role, such as backend developer, so the row outlives a change of staff. The acceptance criterion is a check with a pass condition and a fail condition, written before the code: post a payment-succeeded message with no signature; it passes if the message is refused with status 400 and the booking is still unpaid; it fails if the message is accepted or the booking is marked paid.
A removal needs the same three, because a removed feature can come back. The removed export in the worked register has a requirement (no export route and no scheduled export job), an owner, and a check that a request for the old address gets a 404 and that no export job is scheduled.
Some acceptance criteria can then be written as automated tests. The kit on this page does that for five of them, against a very small invented handler. Each test takes its name from the threat's id and the pass condition in the register, so a failing test points back at the row it came from.
Against the first version of the handler all five tests fail, and against the second all five pass.
The Node.js documentation says that if any tests fail, the process exit code is set to 1. A pipeline step that runs the tests can therefore stop a change that breaks a requirement. Criteria that need a deployed environment, such as the secret scan on a push in T3, stay as written checks that a person runs and records.
What the standards ask for
This section reports what each document says about threat modelling and about written security decisions.
Whether any of them applies to your business depends on what a customer, a contract or an insurer asks you to follow.
Version 1.1 of the framework, dated February 2022, has a practice called Design Software to Meet Security Requirements and Mitigate Security Risks (PW.1). Its task PW.1.1 is to use forms of risk modelling, such as threat modelling, attack modelling or attack surface mapping, to help assess the security risk for the software. Its task PW.1.2 is to track and maintain the software's security requirements, risks and design decisions.
Each task comes with notional implementation examples. NIST describes these as notional examples of types of tools, processes or other methods that could be used to help implement a task, and says no examples or combination of examples are required and the stated examples are not the only feasible options.
PW.1.1 has four. The first is to train the development team, security champions in particular, or collaborate with a risk modelling expert to create models and analyse how to use a risk-based approach to communicate the risks and determine how to address them, including implementing mitigations.
The second is to perform more rigorous assessments for high-risk areas, such as protecting sensitive data and safeguarding identification, authentication and access control, including credential management.
The third is to review vulnerability reports and statistics for previous software to inform the security risk assessment. The fourth is to use data classification methods to identify and characterise each type of data that the software will interact with.
The first of PW.1.2's three examples is to record the response to each risk, including how mitigations are to be achieved and what the rationales are for any approved exceptions to the security requirements, and to add any mitigations to the software's security requirements.
A separate practice covers reviewing the design: PW.2, Review the Software Design to Verify Compliance with Security Requirements and Risk Information. Its task PW.2.1 is to have a qualified person or people who were not involved with the design, automated processes instantiated in the toolchain, or both, review the software design to confirm and enforce that it meets all of the security requirements and satisfactorily addresses the identified risk information.
One of its notional examples is to review the risk models created during software design to determine if they appear to adequately identify the risks.
In ASVS 5.0, the item on threat modelling sits in an appendix, not among the requirements. Appendix D says that while version 5.0 was being prepared, a number of existing and newly suggested items were not included as requirements, and that some have been captured in the appendix.
Under the heading Software Security processes it lists security processes which, in its words, were removed from ASVS 5.0 but are still a good idea. One of them is to verify the use of threat modelling for every design change or sprint planning to identify threats, plan for countermeasures, facilitate appropriate risk responses and guide security testing.
The appendix says the OWASP SAMM project may be a good source for how to effectively implement these processes.
Requirement 13.1.4, at Level 3, refers to a threat model. It asks that the application's documentation defines the secrets that are critical for the security of the application and a schedule for rotating them, based on the organisation's threat model and business requirements.
What ASVS 5.0 does ask for is written decisions. Its chapter "What is the ASVS?" gives permissions, input validation and protective controls around different levels of sensitive data as common examples of requirements whose implementation is complicated and very specific to an application's needs. It says documentation requirements were included which mandate that the application developer's approach and configuration to these sorts of controls must be documented, and that these requirements are intended to document the decisions which the organisation developing the application has taken regarding how to implement certain security requirements.
It says documentation requirements are always in the first section of a chapter, although not every chapter has them, and always have a related implementation requirement.
A threat modelling session is one place where those decisions get made. Four of the documentation requirements a booking application's model would feed:
- 2.1.3 (Level 2): expectations for business logic limits and validations are documented, including both per-user and globally across the application.
- 8.1.1 (Level 1): authorisation documentation defines rules for restricting function-level and data-specific access based on consumer permissions and resource attributes.
- 13.1.1 (Level 2): all communication needs for the application are documented, which must include external services the application relies upon and cases where an end user might be able to provide an external location to which the application will then connect.
- 14.1.1 (Level 2): all sensitive data created and processed by the application has been identified and classified into protection levels.
OWASP's Top 10:2025 says A06, Insecure Design, focuses on risks related to design and architectural flaws, with a call for more use of threat modelling, secure design patterns and reference architectures. Besides using threat modelling for critical parts of the application, its prevention list includes using threat modelling as an educational tool to generate a security mindset.
On OWASP SAMM's site, the threat modelling stream sits under Design and Threat Assessment. The quality criteria for the stream's first maturity level are that you perform threat modelling for high-risk applications, that you use simple threat checklists, such as STRIDE, and that you persist the outcome of a threat model for later use.
NIST IR 8397 puts threat modelling first in its list of eleven recommended verification techniques, as threat modelling to look for design-level security issues.
NIST SP 800-154, a guide to data-centric system threat modelling, is an initial public draft. NIST's page for it gives a publication date of March 2016, says the public comment period is closed, and carries a planning note dated 23 January 2025 saying NIST plans to finalise the publication.
Its abstract describes threat modelling as a form of risk assessment that models aspects of the attack and defence sides of a particular logical entity, such as a piece of data, an application, a host, a system or an environment.
Keeping the model current as the application changes
A threat model describes the system on the day it was drawn.
The cheat sheet says a threat model is something that should be maintained, updated and refined alongside the system. Two of the Manifesto's five values point the same way: a journey of understanding over a security or privacy snapshot, and continuous refinement over a single delivery.
SAMM's second maturity level says to define what triggers updating a threat model, and gives a technology change or deployment of an application in a new environment as examples. Its third says you regularly, for example yearly, review the existing threat models to verify that no new threats are relevant for your applications.
In the walk-through on Microsoft's getting-started page, the team signs off on its threat model, checks the document into source control and continues with development.
For a small team, this page suggests writing a short list of triggers at the top of the register:
- A new flow that crosses a trust boundary: a route, a webhook, an upload, a file sent to someone.
- A new outside service, or a change of provider for an existing one.
- A new role, or a change to what a role may do.
- A new kind of data, especially anything about a person.
- A finding from a test, a code review or an incident that the register did not predict.
- An accepted risk reaching its review date.
Letting the pipeline notice
Keeping the diagram and the register as a file in the repository lets a change to the application and a change to the model travel in the same pull request. The checker in the kit then catches one kind of drift. When a flow that crosses a boundary is added to the file with no threat recorded against it, or a threat points at a flow the diagram no longer has, the checker lists the gap and exits with code 1. In the captured run it reported all eight gaps seeded into a copy of the worked register.
It cannot notice a route that was added to the code and never to the file. That takes the comparison in the next section.
Did we do a good enough job: checking the model against what was built
The fourth question has two halves: is the model any good, and does the application follow it.
On the first, the cheat sheet says the threat model must be reviewed by all stakeholders, not just the development or security teams. The areas it says to focus on include whether the diagram accurately reflects the system, whether a response strategy has been agreed for each identified threat, and whether the agreed mitigations can be tested.
NIST SP 800-218's task PW.2.1 has the design reviewed by a qualified person or people who were not involved with it, by automated processes in the toolchain, or by both.
The second half is a separate job. ASVS 5.0 draws the same line for its own documentation requirements: it says verifying that the documentation is in place and verifying the actual implementation are two separate activities. Microsoft's getting-started page sums up its approach as creating a diagram, identifying threats, mitigating them and validating each mitigation. This page's list for a small team:
- Diagram against the build. List the routes the application serves, the outside hosts it calls, its scheduled jobs and the names of its secrets. Each one should be an element or a flow on the diagram. Anything missing is a flow nobody asked the six questions of.
- Mitigations. Run each acceptance check against the build that will ship, and record pass or fail with the date and the build.
- Removals. Run the check that shows the feature is gone, and look for anything it left behind, such as a scheduled job or a stored file.
- Accepted risks and transfers. Confirm each still has an owner in that role and a review date that has not passed.
- Assumptions. Check each one and write down how. "Customers type card details into the provider's hosted page" is checked by looking for card fields in your own forms and API.
The worked example: class bookings for an invented pottery studio
The original asset on this page is an illustration written for it.
Greenware Studio is an invented pottery studio that sells seats in its classes online. A customer books without an account, pays on a payment provider's hosted page and receives an email with a link for managing the booking. Staff sign in as an instructor or as the studio owner. A payment provider and an email provider sit outside the studio's control.
Its diagram has four external entities, four processes, three data stores, fifteen data flows and three trust boundaries, and nine of the flows cross a boundary. The register holds thirteen threats: three under spoofing, one under tampering, one under repudiation, six under information disclosure, one under denial of service and one under elevation of privilege. Ten are mitigated, one is accepted, one is removed and one is transferred.
Every decision and requirement in the register is this page's worked example for an invented business, not what a standard asks for. The one marked exception is the requirement for the threat of an instructor issuing refunds, which cites two ASVS 5.0 requirements, both at Level 1.
Requirement 8.2.1 asks that function-level access is restricted to consumers with explicit permissions. Requirement 8.3.1 asks that authorisation rules are enforced at a trusted service layer and do not rely on controls that an untrusted consumer could manipulate, such as client-side JavaScript.
The kit: a register file, a checker and five tests
The kit is seven files. threat-register.json is the diagram and the register as data. check-register.mjs reports gaps: a flow that crosses a trust boundary with no threat recorded against it, a threat with no decision, a mitigation or a removal with no requirement, owner or acceptance criterion, an accepted risk with no owner or review date, a transfer that does not name who takes it on or who owns what stays behind, and an id that is not on the diagram. seed-gaps.mjs writes a copy of the register with eight gaps in it. studio-fixtures.mjs, handler-before.mjs and handler-after.mjs are a very small invented request handler in two versions, and acceptance.test.mjs holds five acceptance criteria as tests on the Node.js test runner (node:test). The kit imports only node:fs, node:crypto, node:assert/strict and node:test, and installs no packages.
On Node.js 26.0.0 on macOS, the checker reported no gaps in the worked register and exited with code 0. Against the seeded copy it reported eight gaps and exited with code 1. The five tests all failed against the first version of the handler, with exit code 1, and all passed against the second, with exit code 0.
Every output in the asset was copied from that run by a script. Five lines that showed a local file path were cut, and each cut is marked.
Be exact about what this shows. The checker checks that a register is complete, not that it is good: it cannot tell whether the thirteen threats are the right thirteen. The tests are written for an invented handler made of plain functions with records held in memory, and its webhook signature is the lab's own, not any payment provider's. They show a requirement becoming a test, and say nothing about your application.
What a threat model cannot tell you
That it found everything.
"Have all threats been identified?" is one of the cheat sheet's review questions, and nothing on this page lets a team answer yes with certainty. The Manifesto lists perfect representation among its anti-patterns: it says it is better to create multiple threat modelling representations because there is no single ideal view, and additional representations may illuminate different problems.
A second drawing of the same feature, such as the states a booking moves through, may show threats a data-flow diagram does not.
That the application follows it. A06 says a secure design can still have implementation defects leading to vulnerabilities that may be exploited. A register row marked mitigate records an intention until its acceptance check has been run against the build, and it says nothing about the builds that come after.
That it is still true. A model is as current as its last edit. The assumptions at the top of the worked register are statements someone wrote down, not facts someone checked, until the checks listed under the fourth question have been done.
That it is enough on its own. NIST IR 8397 lists threat modelling as one of eleven recommended techniques, beside automated testing, static code scanning, fuzzing and, if applicable, web application scanners, among others. It says the document does not address the totality of software verification.
What this guide leaves to other guides
Threat modelling touches several neighbouring topics.
Each has a guide of its own in this library, published already or written alongside this one:
- Secure SDLC: where threat modelling sits among the other stages of delivery, from requirements to release approval and vulnerability intake.
- Business logic vulnerabilities: writing the rules of a flow as invariants and playing abuse cases against them with two accounts.
- Broken access control and IDOR: testing whether one account can reach another's records or a higher role's functions.
- Secrets exposure: where keys and tokens leak from, how to find them and what to do when one has leaked.
- Security logging and monitoring: which events to record, how to keep the record intact and what should raise an alert.
Where an outside test fits
A threat model is your own team's account of what could go wrong.
An outside test tries the built application and reports what it found. In a Clever Ops web application and API penetration test, your routes, roles and business rules become the test cases, and the scope asks for your key rules in writing. A diagram and a register like the ones on this page set those out: the roles, the ways in from outside, and the rule each requirement states.
Testing is signed in by default and run from test accounts in every role. Read-only code access to named areas can be added to confirm how a control is enforced, and the report marks which findings were confirmed on the running build. Destructive actions are off by default for real people's accounts and records that existed before the test, and reset, lockout and deletion checks run only on test accounts and test records where the rules of engagement allow them.
The report gives each finding with redacted evidence, its business impact, a fix and the criteria the retest will use.
A test report is evidence for your decisions, not a certificate, and it does not replace the model: a finding the register did not predict is a reason to update it. Very logic-heavy products, such as marketplaces, lending platforms and multi-tenant billing, are scoped individually or referred to a larger firm.
If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
A design activity in which a team draws what it is building, asks what can go wrong, decides what to do about each answer and checks its work. The Threat Modelling Manifesto defines it as analysing representations of a system to highlight concerns about security and privacy characteristics, and frames it with four questions: what are we working on, what can go wrong, what are we going to do about it, and did we do a good enough job.
Using six categories of threat as prompts while you look at a diagram of the system: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. Microsoft's documentation defines each category. OWASP's cheat sheet describes STRIDE as a mnemonic originally developed by Microsoft employees, and says that in practice other approaches may be used alongside or instead of it.
A line that marks where the level of trust changes as data moves, such as between the internet and your application, between ordinary users and administrators, or between your application and another company's service. Microsoft's training material says areas with changing trust zones are the most targeted by attackers and should be carefully designed. When a data flow diagram is used for security, each flow that crosses a boundary is a place to ask what can go wrong.
A short description of someone using a feature in a way nobody intended, such as skipping a payment and telling the application it was paid. OWASP SAMM says misuse and abuse cases describe unintended and malicious use scenarios of the application. A use case describes what a person is meant to do. An abuse case describes someone trying to gain from the same feature, and in a threat register it leads to a decision, a requirement and a test.
No, though one helps. The Manifesto says threat modelling does not depend on one's innate ability or unique mindset and that everyone can and should do it, and SAMM's first maturity level uses simple threat checklists, such as STRIDE. OWASP's cheat sheet also says many developers lack sufficient knowledge and experience in security, and that in many cases the solution lies in inviting members of the security teams to the sessions.
ASVS 5.0 lists it in an appendix, not among its requirements. Appendix D puts the use of threat modelling for every design change or sprint planning among security processes that were removed from ASVS 5.0 but are still a good idea. The standard does ask for documented security decisions, such as the authorisation rules in requirement 8.1.1 at Level 1. On this page's reading, a threat modelling session is one place those decisions get made.
No. A threat model records what a team decided should be true, and a test checks what the built application does. OWASP's Top 10:2025 says a secure design can still have implementation defects leading to vulnerabilities that may be exploited. Each helps the other: the model tells a tester which rules matter, and a finding the model missed is a reason to update it.
When the system changes in a way the diagram would show. OWASP's cheat sheet says a threat model should be maintained, updated and refined alongside the system, and at its second maturity level SAMM says to define what triggers an update, for example a technology change or deployment of an application in a new environment. At its third maturity level SAMM also describes reviewing existing threat models regularly, for example yearly.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.