<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: performing-threat-modeling-in-ci
description: >-
  Integrate threat modeling into CI/CD pipelines using STRIDE analysis, attack
  tree generation, and automated data flow diagram validation. Use pytm and
  Threagile to produce threat models as code.
domain: cybersecurity
subdomain: devsecops
tags:
  - threat-modeling
  - stride
  - pytm
  - threagile
  - data-flow-diagram
  - attack-trees
  - ci-cd
  - security-architecture
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: []
---

# Performing Threat Modeling in CI

## Overview

Threat modeling as code integrates security architecture analysis into CI/CD pipelines.
This skill covers using pytm and Threagile to define data flow diagrams in code,
automatically generate STRIDE threat analyses, and validate architectural security
constraints on every pull request touching infrastructure or API definitions.

Mode: `[MODE: ARCHITECT]` — Automated threat modeling through infrastructure-as-code analysis.

## Prerequisites

- pytm (`pip install pytm`) or Threagile
- Graphviz for diagram rendering
- CI/CD platform with artifact storage
- Architecture documentation in code (OpenAPI, Terraform, etc.)

## Key Concepts

### Threat Model as Code with pytm

```python
# threat_model/model.py
from pytm import TM, Server, Datastore, Dataflow, Boundary, Actor

tm = TM("Web Application Threat Model")
tm.description = "E-commerce platform threat model"
tm.isOrdered = True

# Trust boundaries
internet = Boundary("Internet")
dmz = Boundary("DMZ")
internal = Boundary("Internal Network")
data_tier = Boundary("Data Tier")

# Actors and components
user = Actor("Customer")
user.inBoundary = internet

web_app = Server("Web Application")
web_app.inBoundary = dmz
web_app.OS = "Linux"
web_app.isHardened = True

api = Server("API Gateway")
api.inBoundary = dmz
api.protocol = "HTTPS"
api.authenticatesSource = True

db = Datastore("PostgreSQL")
db.inBoundary = data_tier
db.isEncryptedAtRest = True
db.hasAccessControl = True

# Data flows
user_to_web = Dataflow(user, web_app, "HTTPS Request")
user_to_web.protocol = "HTTPS"
user_to_web.isEncrypted = True

web_to_api = Dataflow(web_app, api, "API Call")
web_to_api.protocol = "HTTPS"
web_to_api.authenticatedWith = True

api_to_db = Dataflow(api, db, "SQL Query")
api_to_db.protocol = "TLS"
api_to_db.sanitizesInput = True

if __name__ == "__main__":
    tm.process()
```

### Threagile YAML Model

```yaml
# threagile-model.yaml
title: E-Commerce Platform
business_criticality: critical

technical_assets:
  web-frontend:
    type: process
    technology: web-application
    internet: true
    encryption: none
    multi_tenant: false
    communication_links:
      api-calls:
        target: api-gateway
        protocol: https
        authentication: token

  api-gateway:
    type: process
    technology: web-service-rest
    encryption: transparent
    communication_links:
      db-queries:
        target: database
        protocol: jdbc-encrypted
        authentication: credentials

  database:
    type: datastore
    technology: database
    encryption: data-with-symmetric-shared-key
    data_assets_stored:
      - customer-pii
      - payment-data

data_assets:
  customer-pii:
    usage: business
    quantity: many
    confidentiality: confidential
    integrity: critical
    availability: operational
```

### CI Pipeline Integration

```yaml
name: Threat Model Validation
on:
  pull_request:
    paths:
      - 'threat_model/**'
      - 'openapi/**'
      - 'terraform/**'

jobs:
  threat-model:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install pytm graphviz
      - name: Generate threat model
        run: |
          cd threat_model
          python model.py --dfd --seq --report threat-report.html
      - name: Validate no high-risk unmitigated threats
        run: |
          python scripts/agent.js --action validate \
            --model threat_model/model.py \
            --output /tmp/validation.json
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: threat-model
          path: |
            threat_model/*.png
            threat_model/threat-report.html
```

### STRIDE Analysis Template

```markdown
| Component | Spoofing | Tampering | Repudiation | Info Disclosure | DoS | Elevation |
|-----------|----------|-----------|-------------|-----------------|-----|-----------|
| Web App   | MFA      | Input val | Audit logs  | TLS + CSP       | WAF | RBAC      |
| API GW    | JWT      | HMAC      | Request log | mTLS            | Rate| Scoped tokens |
| Database  | IAM      | Checksums | Audit trail | Encryption      | HA  | Least priv |
```

## Workflow

### Step 1: Analyze Architecture

```bash
node scripts/agent.js --action analyze --source-dir ./terraform/ --output /tmp/architecture.json
```

### Step 2: Generate STRIDE Analysis

```bash
node scripts/agent.js --action stride --model ./threat_model/model.py --output /tmp/stride.json
```

### Step 3: Validate Threat Mitigations

```bash
node scripts/agent.js --action validate --model ./threat_model/model.py --output /tmp/validation.json
```

## Verification

- [ ] Threat model defined as code in repository
- [ ] Model updated on architecture-changing PRs
- [ ] STRIDE analysis covers all trust boundaries
- [ ] Unmitigated high-risk threats block deployment
- [ ] DFD diagrams generated as CI artifacts
- [ ] Threat model reviewed quarterly

## References

- [pytm Documentation](https://github.com/izar/pytm)
- [Threagile](https://threagile.io/)
- [OWASP Threat Modeling](https://owasp.org/www-community/Threat_Modeling)
- [STRIDE Model](https://learn.microsoft.com/en-us/azure/security/develop/threat-modeling-tool-threats)
