November 18, 2026
Continuous Threat Modeling as Code
A security finding should travel with the code, together with the test that reproduces it. Too often it stays in a report while the…

By shahid.exe
12 min read
A security finding should travel with the code, together with the test that reproduces it. Too often it stays in a report while the application changes.
We built two open-source tools to keep that knowledge usable. GuardLink records threats, controls and data flows as structured comments in your source code, so the threat model lives in the repository and changes with it. cxg (cert-x-gen) is a scanner and test engine that runs checks against an application you are authorized to test. Together they turn a written security claim into an executed test, and bring the result back to the line of code it was about.
This post explains what each tool does, how they connect, and what the loop looks like on a real codebase. It also covers what they don't do.
The problem starts after the review
A security review finds something useful. The finding goes into a report or a ticket, and the code keeps moving. A different developer takes over. A coding agent starts a fresh session. The team may still have the ticket, but it has lost the code context, the assumptions, or the test that made the finding actionable. QA has to work out again how it was tested.
We keep that context in the repository instead. The threat, the affected code, the relevant controls and the verification outcome stay where the next person or agent will look. An unresolved finding can be picked up and tested again without rediscovering it first.
New code still needs analysis, and an old test result still needs a check that it applies. The tools make that work visible. They don't remove it.
GuardLink: the threat model as code
GuardLink parses a small comment language called GAL. Definitions name the things that matter: assets, threats, controls and actors. They live once, in a definitions file inside the project's .guardlink folder:
// @asset GuardLink.Agent_Launcher (#agent-launcher) -- "Spawns child processes for AI coding agents (Claude Code, Cursor, Codex)"
// @threat Child_Process_Injection (#child-proc-injection) [high] cwe:CWE-78 -- "Agent launcher executing attacker-controlled commands via process spawn"
// @control Parameterized_Commands (#param-commands) -- "Using spawn with args array instead of shell string interpolation"// @asset GuardLink.Agent_Launcher (#agent-launcher) -- "Spawns child processes for AI coding agents (Claude Code, Cursor, Codex)"
// @threat Child_Process_Injection (#child-proc-injection) [high] cwe:CWE-78 -- "Agent launcher executing attacker-controlled commands via process spawn"
// @control Parameterized_Commands (#param-commands) -- "Using spawn with args array instead of shell string interpolation"Relationship annotations then sit beside the code they describe. They say what an asset is exposed to, what mitigates it, how data flows and where the trust boundaries are. The definitions above, and the example later in this post, come from GuardLink's own repository, which keeps its own threat model this way.
Because the declarations are structured, ordinary software can query and validate them without asking an LLM to reinterpret prose each time.
guardlink validate .checks syntax and dangling references.guardlink status .summarises what the model holds.guardlink pathswalks the declared data flows and reports routes from an untrusted entry point to a sink with no control on them, with no LLM in the loop.guardlink sarifexports findings as SARIF 2.1.0 for GitHub code scanning.guardlink reportandguardlink dashboardrender the same model as a Markdown report or an HTML dashboard.
The annotations are the model. Reports and diagrams are views of it.
Coding agents carry it forward. guardlink init writes a stamped instruction block into your agent's instruction file, such as CLAUDE.md, AGENTS.md or Cursor's rules, and configures an MCP server where the agent supports one. The agent can ask the model about a file before editing it. In the same session it uses to build a feature or a fix, it can identify threats, annotate them and implement the change. Security reasoning becomes part of development work, and unresolved risks stay visible to whoever comes next. That reasoning still costs tokens and time. It just doesn't need a separate discovery session for every change.
Some decisions stay human. Accepting a risk is a governance decision, not an analysis result. An acceptance has to name the person who signed it, carry an expiry after which the risk comes back, and give a real reason. The MCP tool that records one refuses a call without a human's name and a date, and it tells the agent to ask first. GuardLink's own threat model is candid that this checks the arguments rather than proving the named person agreed. Entitlements go further. An agent can propose one, and only a human accepting it through guardlink entitle writes it to source.
CI enforces what you choose to enforce. guardlink ci is advisory by default. In strict mode it fails on unmitigated exposures, reproduced exploits, acceptances that are not real decisions, drifted anchors, stale claims and parse errors. Severity and scope filters narrow what it gates on, and a minimum coverage floor fails a model too thin to mean anything. A diff check blocks a pull request that adds a new unmitigated exposure:
guardlink ci . --strict --severity critical,high
guardlink diff origin/main --fail-on-newguardlink ci . --strict --severity critical,high
guardlink diff origin/main --fail-on-newGuardLink builds on the annotation grammar of ThreatSpec by Fraser Scott. The core verbs @mitigates, @exposes, @transfers and @accepts come from that work. Threat modelling in source comments is not new. What we focus on is what happens next: connecting those claims to executed tests and recording what the tests showed.
cxg: claims become tests
cxg is a security execution engine written in Rust. It has two surfaces.
cxg scan runs polyglot templates. A detection is real code in the language that fits the problem. That might be Python for a stateful protocol conversation, Go for a database wire protocol, C for a binary handshake, shell to wrap a native tool, or YAML for a simple check. The engine supports 12 languages. A template reads its target from environment variables, does its work, and prints JSON findings. Targets can be a host, a file of hosts, a CIDR range, a URL, or a local command line binary. Output goes to JSON, CSV, SARIF, HTML or Markdown. The detection library lives in its own repository, cert-x-gen-templates, and cxg template updatefetches it.
cxg pentest runs a whitebox pipeline. It reads GuardLink's SARIF export from the codebase, ranks the source code hypotheses against an operator goal, has an AI provider write JavaScript probes that read the target's source, and executes them in authenticated Chromium contexts against a running web app or Electron app. It can also map a Tauri app's IPC surface from source. The engine owns requests, sessions and proof, and it adjudicates every candidate finding. A probe that declares itself confirmed is not taken at its word. Promotion needs observed proof for that class of weakness.
Templates execute as ordinary child processes with your privileges and full network and filesystem access. cxg has no execution sandbox, so review templates before you run them, and use a container or a virtual machine when you need isolation. Only point it at systems you are authorized to test.
How they fit together: the evidence loop
The loop has six steps.
- Model in source. Record assets, threats, controls, flows and boundaries as annotations beside the code, and commit them with it.
- Plan a check. Pick a retained hypothesis.
guardlink hypothesis nextranks the queue. Retests come first, then untested claims by severity, then claims on an undefended path, then unowned ones. - Validate and run.
guardlink translatehands a coding agent the selected exposures and the cxg template contract, and the agent writes the test. Translate only authors templates. You review them, then cxg runs them against an authorized target. - Record evidence. cxg writes a report of what it observed. Findings from its pentest pipeline carry the identity of the claim they tested.
- Update the claim. GuardLink imports the report into its hypothesis ledger, matching each result to its originating annotation.
- Enforce and revisit. CI applies your policy. After a fix, you replay the saved test rather than generating it again. When the code under a claim changes, the claim goes back in the queue.
A remembered risk is not a permanently valid test result. The loop exists so that relevant changes send old outcomes back for review.
Connecting evidence to the right claim
The hard part of the loop is attaching a test result to the claim it actually tested. GuardLink gives every claim a stable identity, a SHA-256 key over the annotation's verb, its arguments, its external references (such as a CWE), its description and its file. Severity and line number are deliberately left out, so moving an annotation or changing a severity does not change the key.
A finding from the cxg pentest pipeline carries the annotation's file and line, its asset and threat, GuardLink's threat id and the claim key. GuardLink's importer resolves each finding by its claim key first:
guardlink hypothesis confirm --from-scan report.jsonguardlink hypothesis confirm --from-scan report.jsonA key that no longer matches any claim is reported as stale, not quietly redirected elsewhere. Only a finding with no key falls back to weaker joins, in order: location, then asset and threat, then CWE. A probe with no originating GuardLink exposure carries no identity, and the importer leaves it unmatched rather than inventing one.
Writing the result back into source is a separate, explicit step. With the write option, only uncontested confirmations verified by claim key become a @confirmed line in the code. Everything else stays in the ledger, and the command prints how to record it by hand.
Templates written for cxg scan name the exposure they test in a header, but scan findings don't carry the claim key. Record those outcomes against the claim's file and line directly, as the worked example below does.
Knowing when to test again
The ledger records each outcome against a hash of the code the claim is anchored to. For languages GuardLink has a grammar for, that hash covers the code's tokens, not its comments or formatting, so editing an annotation or reformatting doesn't count as a change. An exposure is in one of four states.
- Untested. Nothing recorded yet.
- Confirmed. A recorded exploit, with the anchored code unchanged.
- Refuted. Tested and not exploitable, with the anchored code unchanged.
- Retest. It was confirmed, then the code beneath it changed.
When the anchored code changes, an earlier refutation drops back to untested, and an earlier confirmation asks for a retest. These states mark uncertainty. They do not run a new test by themselves.
Replay without regenerating
The templates are ordinary files you can review. guardlink translate writes drafts into a cxg-templates folder inside .guardlink. Once a template has been reviewed and verified, you promote it into the project's curated security suite, a security folder at the repository root unless security_tests_dir in GuardLink's config.json says otherwise. That suite is what you commit and run before review. Drafts and raw scan evidence stay out of the repository. GuardLink's evidence guide recommends git ignoring both the drafts folder and the pentest findings folder, because captured evidence can contain live tokens.
After a developer submits a fix, QA reruns the saved template through cxg. The original threat doesn't need rediscovering, and the test doesn't need another AI generation step. A plain cxg scan of saved templates makes no model calls. In the pentest pipeline, pointing cxg at a saved template folder with authoring switched off skips ranking, generation and AI rewriting of ambiguous probes. Replay still needs a valid target, working authentication and a test that still applies to the current application, and execution has its own cost.
A worked example on GuardLink itself
GuardLink's agent launcher starts coding agent CLIs as child processes. Its source file, launcher.ts, opens with this annotation block, shortened here to the claims about process spawning:
/**
* @exposes #agent-launcher to #child-proc-injection [critical] cwe:CWE-78 -- "spawn/spawnSync execute external binaries"
* @mitigates #agent-launcher against #child-proc-injection using #param-commands -- "Binary names from hardcoded AGENTS registry; no shell interpolation"
* @mitigates #agent-launcher against #cmd-injection using #param-commands -- "Arguments passed as array, not shell string"
* @flows UserPrompt -> #agent-launcher via launchAgent -- "Prompt input path"
* @flows #agent-launcher -> AgentProcess via spawn -- "Process spawn path"
* @boundary #agent-launcher and AgentProcess (#agent-boundary) -- "Trust boundary at process spawn"
*//**
* @exposes #agent-launcher to #child-proc-injection [critical] cwe:CWE-78 -- "spawn/spawnSync execute external binaries"
* @mitigates #agent-launcher against #child-proc-injection using #param-commands -- "Binary names from hardcoded AGENTS registry; no shell interpolation"
* @mitigates #agent-launcher against #cmd-injection using #param-commands -- "Arguments passed as array, not shell string"
* @flows UserPrompt -> #agent-launcher via launchAgent -- "Prompt input path"
* @flows #agent-launcher -> AgentProcess via spawn -- "Process spawn path"
* @boundary #agent-launcher and AgentProcess (#agent-boundary) -- "Trust boundary at process spawn"
*/The threat definition rates child process injection as high. This exposure raises it to critical inline, and the inline severity wins. A mitigation sits right beside the exposure, but a mitigation is a claim too. Nothing has tested it yet, so the exposure is still a hypothesis. Ask what to test next:
$ guardlink hypothesis next .
# state severity asset threat where why
1 untested critical #agent-launcher #child-proc-injection src/agents/launcher.ts:10 unowned
2 untested critical #cli #cmd-injection src/cli/index.ts:39 unowned
3 untested high #agent-launcher #api-key-exposure src/agents/config.ts:13 unowned$ guardlink hypothesis next .
# state severity asset threat where why
1 untested critical #agent-launcher #child-proc-injection src/agents/launcher.ts:10 unowned
2 untested critical #cli #cmd-injection src/cli/index.ts:39 unowned
3 untested high #agent-launcher #api-key-exposure src/agents/config.ts:13 unownedThe launcher's claim is first in the queue. Hand that one exposure to a coding agent and ask for a cxg template:
guardlink translate --headless --agent claude \
--threat child-proc-injection@src/agents/launcher.ts:10guardlink translate --headless --agent claude \
--threat child-proc-injection@src/agents/launcher.ts:10The agent writes a draft into its own folder inside the drafts folder, tagged with the exposure it tests. Read the draft before running anything. Then run it against GuardLink's built CLI as a local target:
mkdir -p .guardlink/pentest-findings
cxg scan --scope "cli://$(pwd)/dist/cli/index.js" \
--context "{\"project_root\": \"$(pwd)\"}" \
--template-dir .guardlink/cxg-templates/<draft-dir> \
--output .guardlink/pentest-findings/launcher --output-format jsonmkdir -p .guardlink/pentest-findings
cxg scan --scope "cli://$(pwd)/dist/cli/index.js" \
--context "{\"project_root\": \"$(pwd)\"}" \
--template-dir .guardlink/cxg-templates/<draft-dir> \
--output .guardlink/pentest-findings/launcher --output-format jsonWhat happens next depends on what the test showed.
If it reproduced, record the confirmation against the claim, with the reproduction as evidence. The write option puts a @confirmed line beneath the exposure, where strict CI fails on it:
guardlink hypothesis confirm src/agents/launcher.ts:10 \
--evidence "<the reproduction>" --writeguardlink hypothesis confirm src/agents/launcher.ts:10 \
--evidence "<the reproduction>" --writeIf the control held, record the refutation with what you tried and what came back. The template is then a candidate for the curated security suite:
guardlink hypothesis refute src/agents/launcher.ts:10 \
--evidence "<what was tried and what came back>"guardlink hypothesis refute src/agents/launcher.ts:10 \
--evidence "<what was tried and what came back>"Either way, the outcome is pinned to the code it was tested against. If someone later edits the spawn logic, the claim goes back in the queue.
GuardLink's repository includes sample output from a real cxg scan of its own CLI, run this way, in the examples folder of its docs. That run executed 13 templates in about 30 seconds.
In the field: legacy open-source codebases
We applied the workflow to large codebases shaped by years of community development: Portainer, Mattermost Desktop, Temporal and ClickHouse. One annotation pass over each built an inventory of candidate threats, and we picked threats from that inventory for targeted cxg testing.
A fresh parse of those annotated models with GuardLink 2.5.0 counts 587 exposure declarations. 193 of them are critical or high.
- Portainer 2.39.2: 13 critical and 58 high, 71 in all.
- Mattermost Desktop: 6 critical and 65 high, 71 in all.
- Temporal: 10 critical and 20 high, 30 in all.
- ClickHouse 26.5.1.882: 3 critical and 18 high, 21 in all.
- Total: 32 critical and 161 high, 193 in all.
These are exposure declarations at source locations. They are hypotheses, not 193 confirmed vulnerabilities, and several can share one root cause.
Targeted testing led to 26 reports across Portainer, Mattermost Desktop and Temporal. The Mattermost Desktop and Temporal reports are private and under triage. Two published Portainer advisories credit our work, alongside other credited researchers.
- GHSA-jmr9–98g4–2phv (high) is a non-admin bind-mount restriction bypass through Docker local driver volumes and automatic Git redeploy, an incomplete fix of two earlier CVEs.
- GHSA-wqqf-pwjh-2hm6 (medium) covers server-side request forgery across several outbound request features, consolidated into one advisory.
The first describes gaps left by earlier fixes. The second brings several reports about outbound requests into a single advisory. Both show why a security control has to be considered across every code path that relies on it.
We kept the annotated Portainer copies private. Publishing them upstream would have exposed unresolved findings. Inside an organisation's own repository, those annotations are exactly what the team should review and commit with the application. Portainer's acknowledgements credit the research outcomes. They don't mean Portainer adopted the workflow.
What this does not do
We'd rather you know the limits up front.
- Annotations are claims. A syntactically valid comment that mentions evidence is not a reproduced vulnerability. Agent instructions guide coverage but don't guarantee it.
- A passing probe is not a secure application. A clean run means no confirmed findings within the run's executed scope and assumptions. An unreachable target, a request that never went out, or a refusal caused by a rate limit proves nothing either way.
- The anchor hash is local. It notices changes to the code under a claim. It can't see a changed dependency, another service, runtime configuration or a change in identity permissions. Pair it with ordinary change review.
- Ledger and source are separate on purpose.
guardlink cireads the source model. A confirmation held only in the hypothesis ledger does not fail CI until it is written to source. - A refusal is not automatically a verified fix. The findings cxg hands GuardLink are confirmed ones only. Refutations and verified mitigations are not imported automatically, so recording a fix as verified is a reviewed step of its own.
- A local command blocks nothing on its own. Enforcement needs the check to be required in your repository and deployment settings.
Getting started
Install GuardLink. It needs Node.js 18 or later.
npm install -g guardlinknpm install -g guardlinkSet it up with annotations inline in source, then let your coding agent add the first pass:
guardlink init --mode inline
guardlink annotate "annotate the HTTP handlers and auth checks"
guardlink validate .
guardlink status .guardlink init --mode inline
guardlink annotate "annotate the HTTP handlers and auth checks"
guardlink validate .
guardlink status .Without the inline mode flag, guardlink init keeps annotations in separate sidecar files under .guardlink instead of in your source comments. This post uses inline mode throughout.
Install cxg with Cargo, Homebrew or the install script:
cargo install cert-x-gen
brew tap bugb-technologies/cxg
brew install cxg
curl -fsSL https://raw.githubusercontent.com/Bugb-Technologies/cert-x-gen/main/install.sh | bashcargo install cert-x-gen
brew tap bugb-technologies/cxg
brew install cxg
curl -fsSL https://raw.githubusercontent.com/Bugb-Technologies/cert-x-gen/main/install.sh | bashThen fetch the detection library:
cxg template updatecxg template updateFrom there, guardlink hypothesis next . tells you what to test first, and guardlink translate turns that claim into a template for review.
Closing
Threat models rot when they live outside the code. Test results go stale when nobody knows which claim they settled. GuardLink keeps the claim beside the code, and cxg turns it into a test with an observed result. The claim identity, the ledger and the anchor hash keep the two connected as the code changes.
Both tools are open source. GuardLink is MIT licensed and its specification is CC-BY-4.0. cxg is Apache 2.0. Read the code, try the loop on an application you own, and tell us where it breaks. Detection templates, integrations and annotation conventions are all open to contribution.
- GuardLink on GitHub and its documentation
- cxg on GitHub and its documentation
- The cxg detection templates