When did you last check your threat model against your code?
A word I wrote ten months ago
In January I published a STRIDE threat model for StokumNET, the small multi-tenant inventory app I build and run alone. It was careful work: trust boundaries, data flows, threats for every part of the system, and for each one a status. Many of those statuses said Implemented.
I wrote that model from the architecture, from what I had designed and believed I had built. I never checked it against the code. Once the first version of StokumNET was running, I turned to the secure development platform I had planned around it from the start, and spent the following months building it stage by stage. One of those stages was exactly that check. Eight controls marked Implemented were missing or weaker in the code, and a line-by-line review found twelve weaknesses in total, two of them high severity.
This post is about that gap, how I closed it in a day, and how I make sure the document and the code can't drift apart quietly again. Every finding here is fixed and released; I don't publish open gaps of a live system.
How I checked
The review was narrow on purpose: the application, not the hosts or the build pipeline, which I had already covered separately. I took a clean export of the main branch of all three repositories (backend in Go, frontend in Next.js, deployment config) and worked through it in three passes.
- Draw what really runs. A data-flow diagram of the live system: browser and iOS app, the internet-facing proxy, a WireGuard tunnel to my private cloud, the router, frontend, API, database, secrets store and logs. Seven trust boundaries, including two that are easy to forget: tenant to tenant inside one database, and role to role inside one tenant.
- STRIDE per element. For each element, the six questions (spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege), answered from the code, not from memory.
- Six focus areas read line by line: token issue and refresh, tenant isolation, CORS, cookies, browser security headers, and rate limiting.

I used an AI assistant for the reading and drafting, under one rule: every finding cites the file and line it comes from, and nothing counts as real until a test fails because of it. That rule mattered more than the tool. It turned "the model thinks there might be a problem" into "here is a request that returns the wrong answer", and it filtered out the plausible-sounding findings that weren't true.
What the code said
Eight controls the January model called Implemented were missing or weaker in the code. None of them was a lie; each was something I had designed, partly built, or assumed a library did for me.
January claim | What the code did |
|---|---|
Row-level security isolates tenants in the database | No row-level security anywhere. Isolation was a |
Login rate limiting | None, in the app or at the proxy |
The activity log covers authentication and permission changes | It covered business actions only: no logins, failures, logouts or token reuse |
No secrets in application logs | One code path logged every cookie, access token included |
HttpOnly cookies and token refresh mitigate token theft | Cookies were scoped to the whole parent domain, and logout did not revoke the refresh token |
CSRF covered by SameSite and origin validation | SameSite yes; origin validation trusted every subdomain, with credentials |
Forwarded headers validated | Read without a trust check (logging only, so low impact) |
Generic error messages to clients | Mostly true; login still returned raw parsing errors |
The review also found things the January model never asked about: no role checks outside user management, refresh tokens that two parallel requests could both redeem, JWT validation that didn't pin the algorithm or audience, tokens accepted on another tenant's address, and leftover debug code with a hard-coded legacy secret.
Twelve findings, fixed in a day
The twelve findings split into 2 high, 5 medium and 5 low. The two highs: logout left the refresh token valid, so a copied session survived for days; and the auth cookies plus a permissive CORS rule meant any script on any sibling subdomain could ask the API for fresh tokens. All twelve were fixed, tested and released within one day, in seven backend releases:
Release | What it fixed |
|---|---|
v1.0.5 | Logout revokes the refresh token; host-only cookies; CORS off unless an exact origin is listed; no tokens or emails in logs |
v1.0.6 | A role for every API route, enforced in middleware; every referenced ID checked against the tenant before a write |
v1.0.7 | Login rate limits in the app, plus per-IP limits at the proxy; unknown emails take as long as known ones |
v1.0.8 | Refresh token redeemed exactly once, in one transaction |
v1.0.9 | Token families: reuse of a spent refresh token revokes the whole session and is logged |
v1.0.10 | One JWT verifier with algorithm, issuer and audience pinned; token must match the tenant's address; debug code and the legacy secret gone |
v1.0.11 | An append-only audit table for logins, failures, logouts, token reuse and role changes |
Two database migrations backed the code up: same-tenant foreign keys, so the database itself now refuses a cross-tenant reference, and the audit table, whose trigger refuses UPDATE and DELETE. Browser security headers, including an enforced Content Security Policy, went in at the proxy without a release.
The pattern behind both, with table names simplified:
-- Every reference carries the tenant, so the database itself
-- refuses a link to another tenant's row.
ALTER TABLE items
ADD CONSTRAINT items_category_same_tenant
FOREIGN KEY (tenant_id, category_id)
REFERENCES categories (tenant_id, id);
-- The audit table refuses changes after the fact.
CREATE TRIGGER auth_events_append_only
BEFORE UPDATE OR DELETE ON auth_events
FOR EACH ROW EXECUTE FUNCTION refuse_change();The composite key is the part I like most: the application still filters by tenant, but a bug in that filter can no longer write a cross-tenant reference. The database says no.
Every fix followed the same path: a test that fails, the patch, a signed commit, a pull request with all scanners green, a signed tag only after the commit is on main, and a deploy that verifies the image signature and SBOM before it runs. On one fix the static analyser in CI caught me building a SQL query from strings, inside a security patch.

The test that lied
My first check of the logout fix passed: I copied the refresh cookie from the browser, logged out, replayed it, and got 401. Later that day I noticed the error text said missing refresh token, not invalid. The browser's developer tools display a cookie value containing a colon with quotes around part of it; I had pasted the quote along with the value, the server discarded the malformed cookie, and the 401 meant nothing. The fix had been right all along, but the evidence wasn't. Since then my test commands strip quotes, check the token's exact shape, and print the server's message, not just the status code.
The refresh cookie has a fixed shape, 32 hex characters, a colon, 64 hex characters, and that colon is what made the browser add quotes. My replay test now looks like this (cookie name simplified):
cookie=$(pbpaste | tr -d '"') # strip the quotes DevTools adds
[[ $cookie =~ ^[0-9a-f]{32}:[0-9a-f]{64}$ ]] \
|| { echo "cookie has the wrong shape"; exit 1; }
curl -s -w '\nHTTP %{http_code}\n' -X POST \
-H "Cookie: refresh=$cookie" \
"https://$TENANT/api/auth/refresh" # print the message, not just the codeA 401 with "invalid refresh token" proves the revocation. A 401 with "missing refresh token" proves nothing.
It happened again
A week later I found the same kind of gap in code the review hadn't read: the backend's startup. The threat model said the backend takes its secrets only from the secrets store. The code agreed, unless the store couldn't be reached: then it fell back to environment variables and accepted whatever signing key it found there, of any length.
Production was safe, but by accident of how it was deployed, not by design. The fix makes the safe outcome the design: if the secrets store is configured and can't be read, the backend refuses to start, and a signing key shorter than 32 bytes is rejected. I proved it the way I now prove every fail-closed path: I triggered the failure on the live system and watched the backend refuse to start.
Keeping it true
The January model went wrong because nothing connected it to the code. A document in a drawer can't notice that the code changed. So the model now lives next to the code and is checked on every pull request, in two ways.
The model as code. The data-flow diagram is a Python file using OWASP pytm: actors, boundaries, processes, data stores and flows, each with the controls I can show evidence for. pytm generates the list of threats that apply. CI regenerates that list on every pull request and compares it with a committed lock file; any difference fails the build. The author reviews the change, records a response (mitigated, accepted, open, not applicable, each with the evidence), and commits the new lock. The lock file's diff in the pull request is the threat-model diff, line by line, for the reviewer.
A trimmed example of what that file looks like:
from pytm import TM, Actor, Boundary, Dataflow, Datastore, Server
tm = TM("StokumNET")
internet = Boundary("Internet")
private = Boundary("Private cloud")
data = Boundary("Tenant data")
browser = Actor("Browser")
browser.inBoundary = internet
api = Server("API (Go)")
api.inBoundary = private
api.controls.authenticatesSource = True # only with evidence: a test or a config line
db = Datastore("PostgreSQL")
db.inBoundary = data
login = Dataflow(browser, api, "POST /api/auth/login")
login.protocol = "HTTPS"
Dataflow(api, db, "tenant-scoped queries")
tm.process()Every controls flag is a claim. Setting one to True removes threats from the generated list, so in review it gets the same question as a status in the old document: where is the evidence?
A drift check. pytm doesn't read code, so a second check watches the paths where security lives: authentication and middleware, routes, cookies, CORS, token code, migrations, deployment files, proxy configuration, and the CI workflows and the check itself. A pull request that touches any of them must either update the model or carry a commit trailer saying why it doesn't:
Threat-Model: none: log message wording onlyThe trailer is cheap to write, which is the point. It turns "I forgot the threat model exists" into a decision someone made and wrote down, visible in the history.
One practical detail: git only treats a line as a trailer when it sits in the last paragraph of the message, in Key: value form. Before pushing, I ask git itself:
$ git log -1 --format=%B | git interpret-trailers --parse
Threat-Model: none: log message wording onlyNo output means the line is just text, and the reason never made it into the history in a form a tool can read.

The twelve findings left a short list of follow-ups, from alerting on token reuse (live since October 31) to a nonce-based CSP. Each one is an issue with acceptance criteria, linked from the model.
Lessons for a threat model in a drawer
- "Implemented" is a claim until there is evidence. Mark each control verified, with the test, log line or config that proves it, or claimed. My merged model now does exactly that, and the claimed rows are the scope of the next review.
- Read the code where trust changes hands. All twelve findings sat on a trust boundary: tenant to tenant, role to role, subdomain to subdomain, session to logout. That's where to spend the reading time.
- Let AI read, but make it cite. An assistant reads three repositories faster than I do. The rule that every finding names its line, and that a failing test makes it real, is what kept the result honest.
- Check your evidence as hard as your fix. A status code alone proved nothing in my logout test. Print what the server says.
- Put the model where the code changes. A threat model that reviewers see in every pull request stays true; one in a wiki ages from the day it's written.
The January model wasn't wrong to exist. It was wrong to stop. The useful version of a threat model is the one that gets checked, and now mine does, on every change.
Member discussion