Threat Modeling as Code: How It Works and Where It Fails
Table of Contents

You're reviewing a pull request that adds a new callback endpoint to a billing service. Somewhere in Confluence, or maybe inside a slide deck from last spring's architecture review, a security engineer wrote down the assumptions that kept this service safe. Nobody linked that document to the ticket, half the people from that meeting have switched teams, and the code looks clean enough to merge.
That gap between what a team agreed to protect and what ships in Git is the reason threat modeling as code exists. Instead of treating security analysis as a one-off workshop artifact that gathers dust, you store the system's security decisions right next to the source code and check them as the codebase evolves.
This practice is often pitched as a way to auto-generate sleek architecture diagrams. That's the wrong mental model. A code-based threat model earns its keep as a versioned decision record with named owners, not a pretty picture, and automation only helps when you know exactly where it creates false confidence.
What Threat Modeling as Code Means and How It Differs
A traditional threat model is a photograph of a whiteboard taken after a design meeting. It captures what people remembered to draw on a Tuesday afternoon, then freezes in place while the service keeps changing. A code-based model works like a building blueprint kept in the same repository as the walls it describes, updated whenever someone moves a doorway or adds a new electrical line.
In one sentence, threat modeling as code stores a system's components, data flows, trust boundaries, assets, and threats as version-controlled files that tools can read, validate, and report on. Because those files live in Git alongside application code, security reviews become part of normal engineering diffs instead of calendar invites scheduled weeks after implementation starts.
| Aspect | Traditional threat modeling | Threat modeling as code |
|---|---|---|
| Where the model lives | Slide decks, wiki pages and whiteboard photos | Version-controlled files in the same repository as the code |
| What triggers an update | A scheduled workshop or a major release | Each pull request that changes components, data flows or trust boundaries |
| Who reviews it | A meeting of architects and security staff | Owners reviewing a diff, plus automated policy checks |
| Audit evidence | A document snapshot dated at review time | Commit history linking threat, decision, control and code change |
| Main failure mode | The model drifts away from the deployed system | The model is only as complete as the files and annotations feeding it |
Why Precision Does Not Guarantee Accuracy
Developers often assume that putting a threat model into YAML, JSON, or Python automatically makes the security analysis stronger. It doesn't. A syntax checker can confirm that your file parses cleanly and that every component has an owner field, while remaining completely blind to a subtle authorization flaw nobody thought to write down.
That's the core trap of code-based models. The output looks crisp, structured, and authoritative, so reviewers let their guard down. If an engineer skips modeling a background worker or forgets to annotate a shared cache, the pipeline stays green and the generated diagram looks finished even though an entire attack path is missing.
A green build on a threat model file proves your syntax and rules match what you declared, not that you thought of every way an attacker can break the service.
Knowing Which Problem You Actually Have
Before you adopt new tooling, look closely at why security gaps slip into your releases today. Teams building mobile or hybrid apps often run into this distinction early when mapping client-side storage, API calls, and native plugin permissions, as detailed in Capgo's guide on risk assessment for Capacitor teams. Knowing where your exposure sits is a separate skill from keeping that map synchronized with your repository.
Decide whether your main gap is stale documentation or missing security judgment. If your engineers already make solid architectural security decisions during design reviews, but those decisions evaporate before code review, keeping the model in code closes that gap directly. If your team hasn't built the habit of spotting abuse cases in the first place, moving a thin analysis into Git just versions the same blind spots faster.
The Four-Stage Workflow Inside a Repository
Structured threat modeling isn't a modern DevOps invention; STRIDE dates back to Microsoft's 1999 internal paper The Threats to Our Products, archived in the CEUR Workshop Proceedings, which instructed product teams to apply six threat categories during design, when trust boundaries can still change cheaply. Those six categories (spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege) gave engineers a finite vocabulary that could later be encoded into structured data.
General references such as the OWASP Threat Modeling Cheat Sheet explain the concepts and questions behind threat modeling, but they stop short of prescribing how the work should live in a repository. For that, a practical workflow can be organized into four stages, and each one maps to a concrete artifact you commit to version control rather than leaving in meeting notes.
- Decompose the application. Break the service into components, data flows, trust boundaries, and sensitive assets, storing the result as a diagram source file (such as a structured YAML definition or PlantUML/Mermaid source) so both humans and parsers read the same topology. This stage works like drawing the system on a whiteboard, except the whiteboard survives the meeting.
- Identify and rank threats. Evaluate each modeled element using STRIDE or another classification method your team already knows, producing a threat list with stable IDs and clear severity rankings. The IDs matter more than they first appear: descriptions get reworded over time, and a fixed identifier is the only way to tell a rewritten sentence from a new threat.
- Define mitigations. Attach specific technical controls to each ranked threat inside a mitigation table or block with named owners, so accountability never floats between teams. A mitigation without a name beside it is a wish, not a control, because nobody has agreed to build, verify, or maintain it.
- Review and validate. Walk through the diff with the component owner and security reviewer before merging, leaving a review record tied to the pull request, originating ticket, and approval state. This is the stage that turns the file into a decision record: months later, anyone can ask who accepted a residual risk, when, and why, and get an answer instead of a shrug.
What a Concrete Model File Looks Like
A single threat-model.yaml file inside a payments service repository shows how those four artifacts fit together. The file declares three components (web-client, checkout-api, and payments-db) so anyone reading the repo sees the full request path without opening a separate wiki.
Next, it defines one data flow, F-07, running from checkout-api to payments-db and carrying tokenized cardholder data across trust boundary TB-02 between the public edge and the internal network. Under threats, entry T-014 records tampering with the payment request and links directly to mitigation M-021 (request payload signing and strict schema validation), a named engineering owner in the file, and verification test PAY-TEST-9. Because every identifier (F-07, TB-02, T-014, M-021, PAY-TEST-9) stays fixed even if someone rewrites a description, a future Git diff shows immediately which flow, boundary, or control changed.
Read top to bottom, the file looks less like a diagram specification and more like an architecture decision record with names attached to each call. One honesty check before you trust it: the format guarantees traceability, not completeness. It records exactly what someone thought to write down, so the review stage is where a second reader earns their place in the loop.
The Storage Rule and Your Maturity Path
The single storage rule that makes repository-based modeling pay off is using a diffable text format. Binary diagram exports and proprietary canvas files hide architectural changes behind opaque commits, whereas plain text lets a pull request highlight a single modified trust boundary and trigger automated risk reporting.

Full pipeline automation is not a day-one requirement. Teams usually pass through four stages of maturity before touching CI gates, and each stage is useful on its own.
| Stage | What it looks like | What it enables |
|---|---|---|
| Ad hoc whiteboard | A diagram drawn in a meeting, photographed and filed | Discussion only, with no reuse |
| STRIDE applied consistently | Every design element checked against the six STRIDE categories | Repeatable reviews across teams |
| Data-flow diagram in the repository | Diagram and threat list stored with the code | Diffs show when a trust boundary changes |
| CI-integrated threat model as code | Model parsed in the pipeline, with milestone reviews | Automated risk reporting on each change |
Your realistic first move is stage three: a repository-stored data-flow diagram and threat list that engineers update alongside architectural pull requests. Notice what jumps between stages two and three. The analysis itself doesn't get smarter, but it gains an owner, a history, and a diff, which is what makes every later stage possible. Before wiring up any bots or linters, ask yourself one checkpoint question: can you point to the exact file in Git that describes your service's most sensitive data flow right now?
Wiring Models Into Pull Requests and Pipelines
Once your team is comfortable keeping a readable model file in Git, continuous integration turns that file from passive documentation into an active guardrail. The goal isn't to replace human security engineers with scripts, but to catch obvious omissions while the developer still has the code open in their editor.
Federal guidance aligns with this engineering-first mindset. NIST SSDF 1.1 explicitly recommends using risk-modeling techniques such as threat modeling, attack modeling, or attack-surface mapping during software development, tying protections to asset significance and adversary capability. Treating your model as a lightweight evidence graph connects each asset to a flow, each flow to a trust boundary, each threat to a control, and each control to a verification test.
Five Steps to Wire the Pipeline
- Co-locate the model with the service. Place
threat-model.yaml(or an equivalent structured format such as ThreatPlaybook, pytm, or Threagile) in the service repository rather than a central security repo, so every code change and model update travels in the same pull request. - Enforce stable identifiers across relationships. Require unique, immutable IDs for components, flows, boundaries, threats, and tests so CI scripts can walk the graph and see which controls are affected when a single service route changes.
- Add a pull request validation job. Configure a fast job in GitHub Actions, GitLab CI, or Jenkins that parses the model file on every PR, checks schema integrity, and flags structural discrepancies between deployment manifests and declared components.
- Write policy rules as clear predicates. Express required standards using policy-as-code checks that evaluate plain boolean logic, such as verifying that all internet-originated flows carrying regulated data enforce authenticated encryption and reference an approved abuse-case review.
- Roll out in warn-only mode before blocking merges. Start with non-blocking PR comments for a two-week shakedown window so developers can fix noisy rules and tune false positives, then switch only your highest-risk predicates to hard merge blocks.
Tracing One Pull Request Through the Checks
Say a developer opens a pull request adding a webhook receiver to the billing service so it can ingest payment settlement events from an external processor. The pull request touches the router configuration and deployment manifest, introducing a public-facing HTTP endpoint.
When the CI job runs, it detects an unmodeled external interface crossing the edge trust boundary with no threat or mitigation listed, and posts a failing status check on the PR. The developer updates threat-model.yaml to register the new webhook flow, adds HMAC signature verification and replay protection to the handler, links the unit test covering forged signatures, and names the billing tech lead as control owner. A security reviewer reads a twelve-line model diff alongside the code diff and clicks approve.

Most engineering teams start with four high-signal checks that catch real architectural drift without burying developers in low-value warnings.
| Change detected | Automated check | Required action |
|---|---|---|
| New external API endpoint | The model must list the endpoint and its authentication method | The owner adds a mitigation or documents an accepted risk |
| Regulated data crosses a trust boundary | Policy requires authenticated encryption and an abuse-case review | A security reviewer approves before merge |
| Component removed from the model but still in the deployment manifest | Drift check fails | The model is updated or the deployment is corrected |
| Mitigation marked done with no linked test | Verification check warns | A test is added or the mitigation is reopened |
Notice the hard boundary of what these checks accomplish. An automated gate confirms that a mitigation is recorded and linked to a test ID, not that the signature check handles timing attacks properly or that the test asserts the right failure path. Verification still depends on an engineer reading the implementation.
Benefits and Limits Teams Should Weigh
Hard numbers on how widely teams practice threat modeling are still early, so treat bold industry claims with skepticism. The 2024-2025 State of Threat Modeling Report collected 73 complete responses, with 60 responses used for company-level analysis. Within that group, STRIDE was the most common individual method, used by about one-third of organizations, while roughly one-fifth aligned with Adam Shostack's four-question framework, and organizations were influenced by approximately four threat-modeling approaches on average.
Two practical lessons follow from those numbers. First, real security programs blend methodologies instead of locking into one textbook standard, which means any machine-readable schema you choose must support custom taxonomies and organizational policies rather than hardcoding STRIDE alone. Second, a sample of 60 company-level responses cannot support sweeping claims about global market adoption, so choose this workflow because it fits your engineering pain points, not because of hype.

Where Code-Based Threat Modeling Pays Off
- Traceable security decisions. Every control maps to a specific commit, pull request, and approver, making it obvious six months later why a rate limit or encryption rule exists.
- Lower architectural drift. Because the model sits next to application code and deployment manifests, engineers spot outdated assumptions during normal feature work rather than during an incident postmortem.
- Reviews inside existing workflows. Developers don't have to switch into separate GRC portals or wait for quarterly review boards to get feedback on a new data flow.
- Audit evidence generated as a byproduct. Instead of scrambling to assemble screenshots before a SOC 2 or ISO 27001 audit, your repository history already links identified risks to implemented controls and tests.
Where the Approach Breaks Down
- Input quality sets the ceiling. Garbage in still yields garbage out; if a team copies boilerplate threats to satisfy a linter, the file adds noise without lowering risk.
- False confidence from polished visuals. Auto-generated diagrams look thorough in executive decks, yet they can hide unmodeled shadow APIs, shared credentials, or third-party webhooks.
- Vanity metrics over decision quality. Teams fall into tracking how many diagrams or YAML files exist across repositories instead of measuring whether high-severity threats resulted in stronger code.
- Ongoing maintenance friction. Every genuine refactor requires updating model entries alongside tests and docs, and tooling across languages and cloud providers remains fragmented enough that many teams maintain custom parser scripts.
Practical rule: Adopt code-based threat models for fast-moving services where architecture shifts every sprint and wiki docs go stale within weeks. Hold off on small, stable internal tools that a tight-knit team can review thoroughly in a thirty-minute conversation.
Who Owns the Model and When Humans Decide
Enthusiasm for threat modeling doesn't automatically translate into working controls. In the 2025 State of Threat Modeling and Security by Design report, a survey of 130 practitioners at organizations with at least 500 developers found that more than three-quarters considered threat modeling a top priority and 80% expected adoption to increase. Yet those numbers tell you nothing about whether models stay accurate after launch, whether recommended mitigations reach production, or whether anyone can prove who signed off on a risk during an audit.
Plenty of teams, including many open-source developers, still run threat modeling informally through conversation rather than documented analysis. Discussions feel easier, more flexible, and lighter on overhead. Here's the uncomfortable truth: if a team skips tough architectural tradeoffs during whiteboard sessions, converting that habit into YAML doesn't fix it. You just automate shallow compliance and bury accountability under pull request noise.
A threat model in a repository works like a flight log, not a map. A map shows terrain once. A flight log records who flew, what decisions they made, and what happened as conditions changed. Treat your model the same way: a decision record with named owners, updated every time the system drifts.
Governance Questions to Answer in Writing
Before enforcing pipeline checks across multiple repositories, write down four operational rules so developers and security reviewers aren't inventing policy mid-sprint:
- Named model ownership. Assign a specific engineering owner (a tech lead or service maintainer, not a vague team alias) to each model file and component entry, responsible for keeping flows current when code changes. When ownership reads "the security team," the practical result is ownership by no one, and entries rot over time.
- Disagreement resolution. Define a short escalation path when a developer thinks a flagged threat is a false positive and a security reviewer disagrees, naming the engineering manager or principal security architect who makes the final call within a fixed SLA. Without this, disputed flags either stall merges for weeks or get dismissed without review to unblock the sprint.
- Human approval thresholds. Separate low-risk changes that automated policy checks can auto-approve from high-impact changes (new authentication flows, cross-tenant data access, or public exposure of regulated records) that always require human sign-off before merge. Automation decides quickly. Humans decide what automation may decide.
- Versioned risk acceptance. Store accepted risks, temporary exceptions, and compensating controls as structured, time-bound records in version control rather than Slack threads, pairing them with an architecture decision record template so expiration dates trigger automatic re-review.
The AI and Agentic System Edge Case
Code diffs assume that system behavior only changes when someone edits source code. AI-enabled applications break that assumption completely. As Microsoft's AI threat modeling guidance explains, AI and ML systems introduce non-deterministic outputs, prompt injection, model poisoning, data leakage, and third-party model risk that supplement rather than replace traditional secure-development methods.
Suppose a product team connects an autonomous support agent to a new internal database tool, swaps an upstream foundation model version, or expands a retrieval pipeline's document index through a configuration panel. No application code changed, so a standard Git-triggered CI check stays silent even though the attack surface shifted dramatically. This is exactly the kind of gap where automation creates false confidence: the pipeline is green, the dashboard is clean, and the exposure sits in a config file nobody thinks to model. Decide in advance who owns and reviews non-code drift across prompts, tool permissions, model versions, and agent capabilities before shipping those systems to production.
A Minimal Decision Record Template
To keep governance lightweight, make every major threat entry answer six fields in plain language: Threat (what can go wrong and on which flow), Owner (the named individual accountable for the outcome), Rationale (why the team chose to mitigate, transfer, or accept the risk), Control (the exact safeguard or compensating measure), Code change (the commit or pull request implementing it), and Verification (the automated test, scanner rule, or runtime check proving the control works).
Six fields sounds like bureaucracy. It isn't. Each one answers a question an auditor or a new teammate will eventually ask, and writing the answer once in the file costs less than reconstructing it from chat history six months later.
Governance check: If an engineer leaves the company next Friday, can their replacement read one pull request and understand why a security exception was granted and when it expires?
Decide Where to Start With Your First Code-Based Model
Don't try to roll out repository-based threat models across forty microservices in a single quarter. Pick one actively developed service that handles sensitive data, such as authentication, billing, or customer records. Capture its core data flows and trust boundaries in a single text file inside that service's repository, wire up one pipeline check, and run the experiment for a focused four-week pilot.
Define your pass/fail criteria before writing the first line of YAML so you judge the practice on real engineering outcomes rather than diagram volume. At the end of those four weeks, your pilot succeeds only if three things happen:
- The model evolves with the code. At least two regular feature pull requests include meaningful updates to the model file without requiring reminders from the security team.
- A check catches a real gap. At least one pull request is flagged, corrected, or blocked because a developer missed a mitigation, authentication detail, or trust boundary update.
- End-to-end audit traceability works. An outsider can pick one control in production and trace it straight back through Git history to the threat, the named decision owner, and a passing verification test.
Hold every commercial tool and open-source script to that exact same test, especially when comparing threat modeling frameworks against your team's existing stack. If a platform generates flashy graphs from your repository but cannot connect a pull request diff to an approved decision and a verification check, it will create busywork instead of security.
Where DevArmor fits into this workflow is closing that design-to-code gap without forcing teams to hand-craft every file from scratch. DevArmor's platform includes Continuous Threat Modeling, Automated Security Reviews, and Implementation Verification, building living context from existing tickets, design documents, and repositories while enforcing Policy-as-Code checks on pull requests with optional merge blocking. Every DevArmor review is traceable to an approved design decision or threat model, and DevArmor does not train any models on customers' code or designs, which is a contractual boundary security teams should verify with any vendor they consider.
Your next step takes ten minutes. List three artifacts you already have for your chosen pilot service: its latest design document, a recent feature ticket, and the service repository itself. Look at which one holds the clearest picture of how sensitive data moves today, and turn that artifact into your first versioned model file.
If you want continuous threat modeling and pull request guardrails without maintaining fragile custom scripts, explore how DevArmor connects your tickets, design documents, and repositories into one living security context. Our platform runs Policy-as-Code checks directly in your workflow, keeps every review traceable to an approved design decision, and never trains models on your code or designs. Visit our site to see how quickly your team can turn existing engineering artifacts into verifiable security reviews.
Table of Contents
Subscribe

