Threat Modeling for Developers: Applying STRIDE During Code Reviews

Threat Modeling for Developers: Applying STRIDE During Code Reviews

Most developers encounter threat modeling as a big-room exercise: a whiteboard session with an architect and a security engineer that produces a document nobody reads after the meeting. The document is filed, the sprint continues, and the threats it identified are never actually addressed in the code.

This guide is about a different approach: making threat modeling a lightweight, continuous practice that happens at the place developers already make security decisions—the pull request. The methodology is STRIDE, and with the right checklists and tooling, a developer who has never done formal threat modeling can apply it in fifteen minutes per PR.

STRIDE in One Page

STRIDE is a threat classification model created at Microsoft in the late 1990s. It names six categories of threats, where the first letter of each forms the acronym:

S — Spoofing | Impersonating another user, service, or system. An attacker claims an identity they don't have. Example: forging a JWT to claim admin privileges.

T — Tampering | Modifying data without authorization. An attacker changes data in transit, at rest, or in memory. Example: altering an order total in a POST body that the server trusts.

R — Repudiation | Performing an action and later denying it. A user or system makes a change, then claims they didn't. Example: a financial transaction with no audit log.

I — Information Disclosure | Exposing data to unauthorized parties. An attacker reads data they shouldn't. Example: verbose error messages that include stack traces with internal paths.

D — Denial of Service | Making a resource unavailable. An attacker exhausts compute, memory, storage, or bandwidth. Example: an API endpoint with no rate limiting accepting expensive database queries.

E — Elevation of Privilege | Gaining more permissions than authorized. An attacker goes from unprivileged to privileged. Example: a user ID parameter that accepts arbitrary values, allowing access to other users' data.

The power of STRIDE is that it is exhaustive at the category level—every security threat fits into at least one of these six buckets. When you review code, you can work through the list systematically instead of trying to recall threats from memory.

Why Code Review Is the Right Place for Threat Modeling

Security issues are cheapest to fix when caught before they are written. Code review is the last gate before code enters the codebase. The developer who wrote the code has the most context about what it does and why—making the review session the optimal time to ask "what could go wrong?"

Traditional post-design threat modeling sessions have a structural problem: they happen weeks after design decisions were made, when changes are expensive and the developer has moved on mentally. PR-level threat modeling happens while the context is fresh and changes are trivial.

The objection is usually "we don't have time." The answer is that you're already reviewing the code—you're already reading it line by line. Adding STRIDE takes ten minutes when you have a checklist. It does not require a whiteboard or a security expert in the room.

STRIDE Checklist: Authentication and Authorization

Use this checklist when reviewing any PR that touches login, session management, JWT handling, API keys, or permission checks.

Spoofing

  • Are credentials validated server-side on every request, not just on login?
  • Are JWTs validated for signature, expiry (exp), issuer (iss), and audience (aud)?
  • Are session tokens unpredictable (cryptographically random, minimum 128 bits)?
  • Does the service validate the Host header to prevent host header injection?
  • Are OAuth state parameters validated to prevent CSRF on the authorization endpoint?

Tampering

  • Are authorization decisions based on server-side data, not user-supplied values?
  • Are object IDs validated against the requesting user's ownership (IDOR check)?
  • Is the request body schema validated before business logic runs?
  • Are signed tokens (JWT, cookies) verified before their contents are trusted?

Repudiation

  • Are all authentication events (login, logout, failed login, password change) logged?
  • Does the log include user ID, IP address, timestamp, and user agent?
  • Are logs immutable (append-only, sent to a separate system the app can't modify)?

Information Disclosure

  • Do error messages reveal internal implementation details (stack traces, SQL, paths)?
  • Are authentication failure messages generic ("invalid credentials") rather than specific ("user not found")?
  • Is sensitive data (passwords, tokens, PII) excluded from logs?
  • Are tokens excluded from URLs (which appear in access logs and browser history)?

Denial of Service

  • Is there rate limiting on login endpoints to prevent brute force?
  • Is there account lockout or progressive delay after repeated failures?
  • Are token refresh endpoints rate limited separately from login?

Elevation of Privilege

  • Does every authorization check verify the calling user's permissions, not just authentication?
  • Is there a test for accessing another user's resource (horizontal privilege escalation)?
  • Is there a test for accessing admin functions as a regular user (vertical privilege escalation)?

STRIDE Checklist: API Endpoints

Use when reviewing PRs that add or modify REST, GraphQL, or gRPC endpoints.

Spoofing

  • Is every endpoint authenticated by default? Are any intentionally public, and is that explicit?
  • Is the authenticated identity sourced from the token/session, not from a request parameter?

Tampering

  • Is all input validated against an explicit schema (types, ranges, required fields)?
  • Are numeric IDs validated to be positive integers before use in queries?
  • Is file upload content validated (MIME type from content, not just file extension)?
  • Are all database queries parameterized or using ORM methods that prevent injection?

Repudiation

  • Are mutating operations (create, update, delete) logged with the actor's identity?
  • Is there a way to correlate a log entry to the specific API call that produced it?

Information Disclosure

  • Does the response schema return only the fields the caller is authorized to see?
  • Are list endpoints filtered to the calling user's scope (not returning all records)?
  • Do 404 responses for private resources look identical to 404s for nonexistent resources?

Denial of Service

  • Are list/search endpoints paginated with enforced maximum page sizes?
  • Are expensive operations (file processing, report generation) rate limited or queued?
  • Is there a request timeout to prevent long-running queries from holding connections?

Elevation of Privilege

  • Are admin-only endpoints decorated with explicit admin authorization, not just authentication?
  • Are bulk operations limited to resources the caller owns?

STRIDE Checklist: Data Storage and Access

Use when reviewing PRs that touch database queries, file storage, caching, or secrets.

Spoofing

  • Is data read from a trusted source (database, cache) rather than user input?
  • Are foreign key relationships enforced at the database level, not only in application code?

Tampering

  • Is data integrity verified with checksums or signatures where tampering would be harmful?
  • Are database migrations reversible? Is there a rollback plan?
  • Is write access to the database limited to the minimum required privilege?

Repudiation

  • Are database-level audit logs enabled for sensitive tables?
  • Are soft deletes used for records that require auditability?

Information Disclosure

  • Are secrets (API keys, passwords, certificates) stored in a secret manager, not in environment variables or config files?
  • Is PII encrypted at rest in the database?
  • Are database connection strings excluded from application logs?
  • Is S3 bucket / blob storage default to private, not public?

Denial of Service

  • Are there indexes on columns used in WHERE clauses in frequently-called queries?
  • Is there a query timeout set at the connection pool level?
  • Is storage growth bounded (cleanup jobs, retention policies, size limits)?

Elevation of Privilege

  • Does the database service account have only SELECT/INSERT/UPDATE on the tables it needs?
  • Is DROP TABLE or TRUNCATE access removed from the application's database user?

Tools: OWASP Threat Dragon

OWASP Threat Dragon is an open-source threat modeling tool that lets you draw data flow diagrams and automatically suggests STRIDE threats for each component.

For teams that want a visual representation alongside their checklist-based reviews:

# Run locally with Docker
docker run -it --rm -p 3000:3000 \
  -e ENCRYPTION_KEYS='[{"isPrimary":true,"id":0,"value":"your-key-here"}]' \
  -e ENCRYPTION_JWT_SIGNING_KEY='your-jwt-key-here' \
  owasp/threat-dragon:latest

Threat Dragon produces threat model files (JSON) that can be committed to the repository alongside the code they model. A PR that introduces a new service should include a threat model update as part of the definition of done.

Tools: Threatspec

Threatspec takes a different approach: you annotate code directly with threat annotations, and the tool generates reports from those annotations.

// @threatspec mitigates Spoofing: JWT token forgery with HMAC signature validation
// @threatspec mitigates Information Disclosure: token contents exposed with using opaque token references
func ValidateAuthToken(tokenString string) (*Claims, error) {
    token, err := jwt.ParseWithClaims(tokenString, &Claims{},
        func(token *jwt.Token) (interface{}, error) {
            if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
                return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
            }
            return jwtSecret, nil
        })
    // ...
}
# @threatspec mitigates Elevation of Privilege: unauthorized resource access with ownership check
# @threatspec accepts Denial of Service: high-traffic endpoint because it's protected by CDN rate limiting
def get_document(document_id: str, current_user: User) -> Document:
    doc = db.get(Document, document_id)
    if doc.owner_id != current_user.id:
        raise PermissionDenied()
    return doc

Generate the report:

pip install threatspec
threatspec run
threatspec report

The report shows a matrix of threats, mitigations, and acceptances across your codebase—giving security teams a programmatic view of coverage without requiring a separate tool.

Automating Threat Review with GitHub PR Templates

A PR template is the lowest-friction way to ensure STRIDE is applied consistently. The author self-certifies the checklist; reviewers see immediately what was and wasn't considered.

Create .github/pull_request_template.md:

## Description
<!-- What does this PR do? -->

## Security Review (required for changes touching auth, data access, APIs, or infrastructure)

If this PR does NOT touch security-sensitive code, check this box and skip the rest:
- [ ] Not security-sensitive (no auth, no data access, no API changes, no dependency updates)

### STRIDE Threat Checklist

**What attack surfaces does this change create or modify?**
<!-- e.g., "New POST /api/upload endpoint", "Modified JWT validation", "Added S3 write access" -->

**Spoofing** — Could an attacker impersonate a user or service?
- [ ] Considered | [ ] N/A | Notes: 

**Tampering** — Could an attacker modify data without authorization?
- [ ] Considered | [ ] N/A | Notes: 

**Repudiation** — Could an actor deny performing an action?
- [ ] Considered | [ ] N/A | Notes: 

**Information Disclosure** — Could an attacker read data they shouldn't?
- [ ] Considered | [ ] N/A | Notes: 

**Denial of Service** — Could an attacker make a resource unavailable?
- [ ] Considered | [ ] N/A | Notes: 

**Elevation of Privilege** — Could an attacker gain more permissions than authorized?
- [ ] Considered | [ ] N/A | Notes: 

### Mitigations Applied
<!-- List specific mitigations added in this PR -->

### Accepted Risks
<!-- List any threats identified but not addressed, with justification -->

Enforcing the Template in CI

You can fail a CI check if the security section is incomplete for PRs that touch sensitive paths:

# .github/workflows/security-review-check.yml
name: Security Review Check

on:
  pull_request:
    paths:
      - 'src/auth/**'
      - 'src/api/**'
      - 'src/db/**'
      - '**/middleware/**'

jobs:
  check-security-review:
    runs-on: ubuntu-latest
    steps:
      - name: Check PR description for security review
        uses: actions/github-script@v7
        with:
          script: |
            const body = context.payload.pull_request.body || '';
            
            // Check if author marked it as non-security-sensitive
            if (body.includes('- [x] Not security-sensitive')) {
              console.log('PR marked as non-security-sensitive. Skipping check.');
              return;
            }
            
            // Check STRIDE categories are addressed
            const threats = ['Spoofing', 'Tampering', 'Repudiation', 
                           'Information Disclosure', 'Denial of Service', 
                           'Elevation of Privilege'];
            
            const missing = threats.filter(threat => {
              // Either "[x] Considered" or "[x] N/A" must be checked
              const consideredPattern = new RegExp(
                `\\*\\*${threat}\\*\\*[\\s\\S]*?\\- \\[x\\]`, 'i'
              );
              return !consideredPattern.test(body);
            });
            
            if (missing.length > 0) {
              core.setFailed(
                `Security review incomplete. Missing STRIDE categories: ${missing.join(', ')}. ` +
                'Please complete the security review section of the PR template, or mark the PR as non-security-sensitive.'
              );
            } else {
              console.log('Security review complete.');
            }

Making This Stick

The biggest failure mode for security checklists is that they become checkbox theater—developers tick boxes without thinking, reviewers approve without reading. Three things prevent this:

Make the author do the work. The PR template puts the checklist on the author, not the reviewer. The author has the most context and is forced to think through the threats they introduced.

Review findings, not checkboxes. Reviewers should look at the "Notes" and "Accepted Risks" sections, not just whether boxes are checked. A note that says "rate limiting via CloudFlare" for a DoS threat is meaningful. An empty checkbox is not.

Track accepted risks. Every threat that is identified but not mitigated should be logged—as a GitHub issue, Jira ticket, or entry in the threat model file. If accepted risks are never tracked, they never get addressed.

STRIDE isn't a silver bullet. It won't catch every vulnerability. But it systematically ensures that the person writing the code has thought about the six most common categories of security failures before the code reaches production. That alone reduces the "I didn't think about that" class of vulnerabilities—which, in the author's experience, is the most common class of all.

Read more

Start now free