Secure coding with Claude Code means catching vulnerabilities as code is written, not after it reaches a pull request. The security-guidance plugin reviews Claude’s own changes for injection, unsafe deserialization, and DOM risks, fixing issues in the same session before human reviewers ever see them.

Secure Coding: What You’ll Learn
Secure coding becomes practical when Claude reviews its own work at three checkpoints during every session. This guide covers the security-guidance plugin, custom rule files, vulnerability pattern categories, and how secure coding fits into a broader defense-in-depth workflow alongside CI scanners and pull request reviews.
What Secure Coding with Claude Code Means
Secure coding is the practice of writing code that resists exploitation from the start. With Claude Code, this means the AI assistant does not just generate code and move on. It actively reviews what it writes for common vulnerability classes and fixes problems in the same session.
The security-guidance plugin is the tool that makes this possible. Once installed, it runs automatically with no command to remember and nothing to invoke. Claude reviews its own file edits, turn-level changes, and commits for security issues before they leave your editor.
This matters because traditional security review happens late. Code reaches a pull request, a human reviewer checks it, and vulnerabilities are found days or weeks after they were introduced. The plugin shifts that review left, catching issues while the code is still being shaped.
The plugin is built entirely on hooks, the mechanism for running custom code at specific points in Claude’s processing loop. It registers hooks for session start, prompt submission, post-edit, end-of-turn, and post-commit events. This design means the review happens inline with the development workflow.
None of the review layers block writes or commits. Findings reach the writing Claude as instructions, and Claude addresses them in the conversation. The review model can miss issues. Treat the plugin as one layer of defense in depth, not a complete security solution.
The Security Guidance Plugin
The security-guidance plugin is an official Anthropic plugin distributed through the Claude Plugins marketplace. It makes Claude review its own code changes for common vulnerabilities while it works and fix what it finds in the same session.
Before installing, confirm the prerequisites. You need Claude Code CLI version 2.1.144 or later, Python 3.8 or later on your PATH, and a git repository for your working directory. The end-of-turn and commit reviews diff against git state and skip silently outside a repository.
On first run, the plugin creates a virtual environment under ~/.claude/security/ and installs the Claude Agent SDK. This requires pip and network access. If that install fails, the commit review falls back to a single-shot review instead of the agentic one.
Installing the Plugin
In a Claude Code session, install from the official Anthropic marketplace:
/plugin install security-guidance@claude-plugins-official
The install prompts for a scope. Choose user scope to write the plugin to your user settings, so it loads in every new local session on your machine. If Claude Code reports that the marketplace is not found, run this first:
/plugin marketplace add anthropics/claude-plugins-official
Then activate it in the current session without a restart:
/reload-plugins
Enabling in Cloud Sessions and Shared Repositories
User-scoped plugins do not carry into Claude Code on the web, because those sessions run on Anthropic infrastructure. To enable the plugin there, or for everyone who clones a repository, declare it in checked-in project settings:
{
"enabledPlugins": {
"security-guidance@claude-plugins-official": true
}
}
Administrators can enable the plugin organization-wide by setting enabledPlugins in managed settings. This ensures every team member gets secure coding review without individual installation.
Three Layers of Automatic Review
The plugin reviews Claude’s work at three points, each at a different depth. Understanding these layers is essential for effective secure coding with Claude Code.
Layer 1: Per-Edit Pattern Check
When Claude writes to a file, the plugin scans the new content for known risky patterns. This is a pattern match with no model call, so it adds no usage cost. The check runs after the edit lands and appends warnings to Claude’s context for the next step.
Each warning fires once per pattern per file per session, so repeat matches in the same file do not flood the conversation. This layer catches the most common dangerous calls instantly and deterministically.
Pattern categories include dynamic code execution like eval(), new Function, os.system, and child_process.exec. It also catches unsafe deserialization with pickle, DOM injection through dangerouslySetInnerHTML and document.write, and edits to workflow files under .github/workflows/ that can grant repository-level permissions.
Layer 2: End-of-Turn Review
A turn is one round of Claude responding. After each turn, the plugin computes a git diff of everything that changed in the working tree during the turn. This includes changes from Claude’s edit tools, Bash commands, and subagents. The diff goes to a separate Claude review focused on security.
The review runs in the background, so Claude’s reply is not delayed. If the review finds issues, Claude is re-prompted with the findings and addresses them as a follow-up. You see both the finding and Claude’s resolution directly in your session.
This layer catches issues a string match cannot detect. Examples include authorization bypass, insecure direct object references, injection, server-side request forgery, and weak cryptography. The review covers up to 30 changed files per turn and fires at most three times in a row before yielding back to you.
Layer 3: Commit and Push Review
When Claude runs git commit or git push through its Bash tool, the plugin runs a deeper agentic review of the change in the background. This review reads surrounding code, including callers, sanitizers, and related files, to decide whether a finding is real before reporting it.
The extra context keeps false positives low on patterns that look dangerous in isolation but are safe in your codebase. This layer fires only on commits and pushes Claude makes through its Bash tool. Commits you run from your own shell are not reviewed.
Commit and push reviews are capped at 20 per rolling hour. If the commit review’s findings duplicate what the end-of-turn review already reported, Claude is not re-prompted, so a clean commit produces no visible output from this layer.
Review Independence
The plugin does not ask the same Claude instance that wrote the code to grade itself. The per-edit check is a deterministic string match with no model involved. The end-of-turn and commit reviews run as a separate Claude call with a fresh context and a security-focused prompt.
The reviewer starts from the diff, has no investment in the original approach, and is instructed only to find problems. This separation is a core principle of secure coding review: the reviewer should not be biased by having written the code.
Vulnerability Patterns Claude Detects
The plugin catches a range of vulnerability classes across its three layers. Understanding these patterns helps you know what secure coding coverage you get and where you still need CI scanners.
Dynamic Code Execution
The per-edit check flags calls that execute arbitrary code at runtime. This includes JavaScript eval() and new Function, Python os.system, and Node.js child_process.exec. These calls are dangerous because they can execute attacker-controlled input if not properly sanitized.
Unsafe Deserialization
The plugin flags pickle and similar deserialization calls that can execute arbitrary code when processing untrusted data. Deserialization vulnerabilities are a critical class because a crafted payload can achieve remote code execution on the server.
DOM Injection
In frontend code, the plugin catches DOM injection patterns including dangerouslySetInnerHTML, .innerHTML = assignments, and document.write. These can introduce cross-site scripting vulnerabilities if the injected content includes user-supplied data.
Workflow File Edits
Edits under .github/workflows/ receive special attention because they can grant repository-level permissions. A compromised workflow file can leak secrets, modify releases, or escalate access across an organization.
Authorization and Logic Flaws
The end-of-turn model review catches issues that pattern matching cannot. Authorization bypass happens when a route or function fails to check user permissions. Insecure direct object references occur when user-supplied identifiers access objects without ownership verification.
The review also detects injection beyond simple string patterns, server-side request forgery where the server makes requests to attacker-controlled URLs, and weak cryptography such as deprecated hash functions or hardcoded keys. These require contextual understanding, which is why they need a model-backed review rather than a pattern match.
Writing Your Own Security Rules
The plugin has two extension points. You can add a Markdown guidance file for the model-backed reviews and a YAML or JSON patterns file for the per-edit string match. Both are additive, meaning you can add checks but cannot disable built-in ones from these files.
Guidance for Model-Backed Reviews
Create .claude/claude-security-guidance.md in your project and describe your threat model and review checklist in plain language. The model-backed reviews load it as additional context alongside the built-in vulnerability checklist.
# Security guidance for this repo
- Do not log customer_id or account_number at INFO level or above.
- All routes under /admin must call require_role("admin") before any database read.
- Use crypto.timingSafeEqual for token comparison instead of ===.
These rules are guidance for the reviewer, not deterministic guardrails. The plugin surfaces violations as findings for Claude to fix, but it does not block writes or guarantee every violation is caught. A rule that says to ignore a vulnerability class does not suppress those findings. For hard enforcement, pair the plugin with a hook that blocks the edit or a CI check.
Custom Per-Edit Patterns
Create .claude/security-patterns.yaml to add regex or substring rules to the per-edit pattern check. These run as deterministic string matches alongside the built-in patterns:
patterns:
- rule_name: internal_api_key
substrings: ["sk_live_", "AKIA"]
reminder: "Hardcoded API key prefix. Load credentials from the secret manager."
- rule_name: tenant_unfiltered_query
regex: "\.objects\.all\(\)"
paths: ["**/src/tenants/**"]
reminder: "Multi-tenant code must filter by org_id."
The rule_name is the identifier shown in the warning. The reminder is warning text appended to Claude’s context, capped at 1 KB. You provide either regex or substrings, and optional paths and exclude_paths glob patterns to scope the rule.
The plugin loads up to 50 custom rules and skips regexes that look prone to catastrophic backtracking. It also reads .claude/security-patterns.yml and .claude/security-patterns.json with the same schema. JSON works on any Python install, while the YAML forms require PyYAML to be importable.
Rule File Lookup Locations
The plugin looks for guidance and pattern files in three locations. The user scope at ~/.claude/ applies to every project on your machine. The project scope at .claude/ is checked in with the repository. The project local scope at .claude/*.local.md is gitignored for personal overrides.
The plugin loads all locations that exist and concatenates them, with a combined cap of 8 KB for the guidance file. Administrators can distribute organization-wide rules by pushing the user-scope file through device management.
The Defense-in-Depth Security Stack
The plugin is one layer in a defense-in-depth approach. It catches issues earliest, while code is still in the editor, but it is not a guarantee and does not replace later checks. A typical secure coding stack has four stages.
The in-session stage is the security guidance plugin, which catches common vulnerabilities in code Claude writes and fixes them in the same session. The on-demand stage is the /security-review command, which provides a one-time security pass on the current branch when you ask for it.
The pull request stage is Code Review, available on Team and Enterprise plans. It runs multi-agent correctness and security review with full codebase context. The CI stage is your existing static analysis and dependency scanners, which handle language-specific rules, supply-chain checks, and policy enforcement the plugin does not attempt.
Each later stage catches what earlier ones miss. The plugin’s value is reducing the volume that reaches them, not eliminating the need for them. Secure coding with Claude Code is about early detection, not replacing your entire security pipeline.
How This Differs from Permissions
Secure coding with the security-guidance plugin is fundamentally different from Claude Code’s permissions system. The permissions system controls what tools Claude can use and how to restrict them. It governs access: which files Claude can read and write, which Bash commands it can run, and whether actions require approval.
Permissions answer questions like “Can Claude run this command?” and “Should Claude edit this file?” They use allow rules, deny rules, and permission modes like plan mode and accept edits to control Claude’s capabilities.
Secure coding, by contrast, answers “Is the code Claude wrote safe?” The security-guidance plugin does not gate Claude’s tools. It reviews the output of those tools for vulnerabilities. Claude can have full write access and still get secure coding review, because the plugin examines what was written, not whether writing was permitted.
If you want to restrict what Claude can do, read the permissions guide. If you want Claude to review what it wrote for security flaws, this is the right guide. Both are important for a complete security posture, and they complement each other rather than overlapping.
Team and Organizational Security Practices
For teams adopting secure coding with Claude Code, several practices strengthen the workflow. Use managed settings to enforce the plugin across the organization, so every developer gets review without individual setup.
Share approved custom rule files through version control. Your .claude/security-patterns.yaml and .claude/claude-security-guidance.md files become part of the repository, ensuring consistent threat models across the team.
Monitor Claude Code usage through OpenTelemetry metrics, which let you track how often reviews fire and what they find. You can also audit or block settings changes during sessions with ConfigChange hooks, preventing unauthorized permission relaxation.
Review all suggested changes before approval, even with the plugin active. Use project-specific permission settings for sensitive repositories. Consider using dev containers for additional isolation when working with untrusted content or external services.
Regularly audit your permission settings with the /permissions command. The plugin catches code-level vulnerabilities, but permission configuration is your responsibility and determines Claude’s overall access scope.
Usage Cost and Model Configuration
The per-edit pattern check makes no model call and adds no cost. The end-of-turn and commit reviews each spend additional model usage that counts toward your usage like any other Claude request.
Both model-backed reviews use Claude Opus 4.7 by default. You can choose a different model by setting environment variables. Use SECURITY_REVIEW_MODEL for the end-of-turn review and SG_AGENTIC_MODEL for the commit review. The commit review is agentic and may take several model turns per commit, capped at 20 reviews per rolling hour.
Expect roughly one review call per turn that changes files and one deeper review per commit, both subject to the caps. The plugin is available on all plans, so there is no tier restriction on secure coding review.
Disabling and Troubleshooting
To turn off individual layers while keeping the rest, set environment variables. ENABLE_PATTERN_RULES=0 disables the per-edit check. ENABLE_STOP_REVIEW=0 disables the end-of-turn review. ENABLE_COMMIT_REVIEW=0 disables the commit and push review. ENABLE_CODE_SECURITY_REVIEW=0 disables all model-backed reviews at once, and SECURITY_GUIDANCE_DISABLE=1 disables the plugin entirely.
You can also pause the plugin with /plugin disable security-guidance@claude-plugins-official or remove it with /plugin uninstall. If the plugin was enabled through project settings, disabling it writes an override to your local settings rather than editing the checked-in file.
The plugin writes runtime diagnostics to ~/.claude/security/log.txt. Check there first if reviews are not appearing. Common reasons for silent skips include working outside a git repository, having no Anthropic authentication for model-backed reviews, or having a YAML patterns file without PyYAML installed.
For more on the security foundation behind Claude Code, including SOC 2 Type 2 and ISO 27001 certifications, visit the Anthropic Trust Center.
A Worked Example
Imagine you are building a Python web API with an admin route. You ask Claude Code to add an endpoint that returns user data by ID. Claude writes the route handler, queries the database, and returns the result as JSON.
The per-edit pattern check fires immediately if Claude uses os.system to run a database command instead of a parameterized query, or if it logs the full request body at INFO level. The warning appears in Claude’s context before the next step.
At the end of the turn, the model review examines the full diff. It notices that the route does not check whether the requesting user has admin privileges, flagging an authorization bypass. It also catches that the user ID parameter is passed directly into the query without parameterization, an injection risk.
Claude is re-prompted with both findings. It adds a require_role("admin") check before the database read and switches to a parameterized query. The fix happens in the same session, before any commit.
When Claude commits the change, the commit review reads the surrounding code. It checks whether require_role is properly implemented elsewhere in the codebase, whether other admin routes follow the same pattern, and whether the parameterized query is used consistently. Finding no additional issues, the commit proceeds cleanly.
This example shows how the three layers work together. The pattern check catches the obvious dangerous call instantly. The end-of-turn review catches the logic flaw that pattern matching cannot see. The commit review validates the fix against the broader codebase. Each layer adds depth without blocking the workflow.
Secure Coding: Common Mistakes to Avoid
Even with the security-guidance plugin active, certain misconceptions can undermine your secure coding workflow. Avoid these pitfalls to get the most from the tool.
- Treating the plugin as a complete security solution. The plugin is one layer of defense in depth. It does not replace CI scanners, dependency checks, or human code review. It reduces what reaches later stages, not eliminates the need for them.
- Forgetting to install Python and pip. The plugin requires Python 3.8 or later on your PATH. Without it, the virtual environment creation fails and the agentic commit review falls back to a weaker single-shot mode or skips entirely.
- Working outside a git repository. The end-of-turn and commit reviews require git state to compute diffs. If your directory is not a git repo, those layers skip silently and only the per-edit pattern check runs, losing the model-backed review entirely.
- Expecting custom guidance to suppress findings. A rule that says to ignore a vulnerability class does not suppress those findings. The guidance is additive only. For hard enforcement, pair the plugin with a blocking hook or a CI check.
Secure Coding: Best Practices
To get the most from secure coding with Claude Code, follow these practices. They maximize coverage while keeping the workflow efficient.
- Install the plugin at user scope. This loads it in every new local session automatically. You never forget to enable it, and secure coding review becomes the default rather than an afterthought.
- Check in custom rule files. Commit
.claude/security-patterns.yamland.claude/claude-security-guidance.mdto your repository. This ensures every team member gets the same threat model and pattern coverage without individual configuration. - Write specific, actionable guidance. Generic rules like “be secure” add little value. Write concrete checklist items: “all admin routes must call require_role,” “never log customer_id at INFO level,” “use timingSafeEqual for token comparison.”
- Use JSON for patterns if PyYAML is missing. The YAML pattern file requires PyYAML to be importable. If your environment lacks it, use
.claude/security-patterns.jsoninstead, which works on any Python install. - Pair with permissions for full coverage. The plugin reviews code for vulnerabilities. Permissions control what Claude can do. Use both together for a complete security posture. Review your permission settings regularly with the
/permissionscommand.
Secure Coding: Frequently Asked Questions
Does the security-guidance plugin block writes or commits?
No. None of the three review layers block writes or commits. Findings reach the writing Claude as instructions, and Claude addresses them in the conversation. The review model can miss issues, so treat it as defense in depth.
Does the per-edit pattern check cost usage?
No. The per-edit pattern check is a deterministic string match with no model call. It adds no usage cost. Only the end-of-turn and commit reviews spend model usage, capped at three per turn and twenty per hour respectively.
Can I add my own vulnerability patterns?
Yes. Create .claude/security-patterns.yaml with regex or substring rules. The plugin loads up to 50 custom rules alongside built-in patterns. You can also add Markdown guidance for the model-backed reviews in .claude/claude-security-guidance.md.
What Python version does the plugin require?
Python 3.8 or later must be on your PATH. The plugin tries python3, python, and py -3 in that order. It needs pip and network access on first run to install the Claude Agent SDK.
How is this different from the permissions system?
Permissions control what tools Claude can use and which actions require approval. The security-guidance plugin reviews the code Claude writes for vulnerabilities. Permissions gate access; secure coding reviews output. Both complement each other.
These frequently asked questions cover the most common points of confusion. If you have deeper questions, the plugin source on GitHub is a working example of running a separate model call from a hook.
Secure coding with Claude Code means the security-guidance plugin reviews every edit, turn, and commit for vulnerabilities before code leaves your editor. Install it, add custom rules, and pair it with permissions and CI scanners for a complete defense-in-depth workflow.
Continue Learning
- Claude Code Permissions: Easy Security Guide — Control what tools Claude can use and which actions require approval.
- Claude Code Extensibility: Best Decision Guide — Compare skills, hooks, and subagents for extending Claude Code.
- Claude Code Enterprise: Best Team Setup Guide — Set up managed settings, audit logging, and team-wide security policies.