feat: security scanning workflow (auditor + patcher + gate hook)

- security-hardening.md Part 4: PR security review workflow
  3-agent pipeline: scan → data flow trace → patch
  Tableau par type de changement (auth, DB, upload, deps)
  Hook pre-push git pour alerter sur fichiers sensibles
- security-patcher agent: applique les findings du security-auditor
  Propose avant d'écrire, jamais en autonomie (human approval gate)
  Séparation nette detect vs patch
- security-gate.sh hook: PreToolUse, 7 patterns vulnérables bloqués
  SQLi, XSS innerHTML, secrets hardcodés, eval() dynamique,
  hash faible (MD5/SHA1 password), command injection, path traversal
  Complément de dangerous-actions-blocker.sh (ops système)
- Claude Code Security (research preview) documentée dans security-hardening.md
  Comparaison Security Auditor Agent vs feature Anthropic
- reference.yaml: 4 nouvelles entrées indexées

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Florian BRUNIAUX 2026-02-22 15:21:35 +01:00
parent ac50ee7ad8
commit 9218ab37d6
5 changed files with 432 additions and 1 deletions

View file

@ -8,6 +8,52 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added
- **guide/workflows/plan-driven.md — Section "Advanced: Custom Markdown Plans (Boris Tane Pattern)"** (+169 lignes)
- Workflow 3 phases : Research emphatic → Annotation Cycle → Implémentation mécanique
- Table comparative `/plan` natif vs custom `.md` (critères de choix)
- Diagramme Annotation Cycle avec boucle, guard prompt et critères de sortie
- Phase 1 : pourquoi le langage emphatique change le comportement de Claude
- Phase 2 : structure plan.md Aristote-ready, exit criteria, quote Boris Tane
- Phase 3 : mindset mécanique, feedback terse
- Table techniques complémentaires (cherry-picking, scope trimming, revert & re-scope)
- Source : Boris Tane (Engineering Lead @ Cloudflare), Feb 2026
- **guide/ultimate-guide.md — AI Code Disclosure Policy** (section 3.5)
- Seuil >10 lignes consécutives = déclaration obligatoire
- Template PR : "Ce que l'IA a fait / Ce que j'ai fait"
- Graduated enforcement par niveau (junior → senior)
- Anti-pattern "vibe coding caché" documenté
- **guide/ultimate-guide.md — claude-mem avec Gemini** (section claude-mem)
- Alternative Gemini 2.5 Flash : $14/mois vs Haiku $102/mois (-86%)
- Instructions de configuration via dashboard localhost:37777
- Tableau comparatif modèles avec coût mensuel mesuré (400 sessions/mois)
- **guide/ultimate-guide.md — claude-mem gotchas critiques** (section claude-mem)
- Hooks coexistence : avant/après JSON, risque d'overwrite silencieux documenté
- Fail-open v9.1.0+ : worker down ne bloque pas Claude Code, restart instructions
- **guide/methodologies.md** : cross-reference vers Boris Tane Pattern depuis section Plan-First
- **machine-readable/reference.yaml** : 4 nouvelles entrées (`annotation_cycle_pattern`, `custom_markdown_plans`, `boris_tane_source`, `boris_tane_author`)
- **docs/resource-evaluations/boris-tane-how-i-use-claude-code.md** : évaluation formelle (score 4/5, fact-check, décision d'intégration)
- **docs/resource-evaluations/aristote-ai-instructions-patterns.md** : analyse patterns production Méthode Aristote (24 fichiers ai-instructions)
- **guide/security-hardening.md — Part 4: Integration** (+104 lignes)
- **4.1 PR Security Review Workflow** : pipeline 3 agents (security-auditor → data flow trace → security-patcher), prompt prêts à l'emploi
- Tableau par type de changement (API endpoint, DB query, auth, file upload, lib tiers) avec niveaux de risque
- Hook `pre-push` git pour alerter sur les fichiers sensibles (auth, payment, token, session)
- **Claude Code Security (Research Preview)** : présentation de la feature Anthropic en waitlist, comparaison avec Security Auditor Agent
- **examples/agents/security-patcher.md** : nouvel agent (companion du security-auditor)
- Scope limité : applique les patches identifiés par security-auditor, jamais en autonomie
- Séparation des responsabilités explicite : auditor détecte, patcher corrige
- Propose les patches pour review humaine, n'applique rien sans approbation
- **examples/hooks/bash/security-gate.sh** : nouveau hook PreToolUse
- Détecte les anti-patterns de sécurité applicative avant écriture dans les fichiers source
- Complémente `dangerous-actions-blocker.sh` (ops système) — focus sur le code applicatif
- Exit 0 = allow, Exit 2 = block avec message contextuel
- **guide/workflows/pdf-generation.md** : diagramme "Output Formats & Commands" (+48 lignes)
- Table ASCII 3 colonnes (format / commande / sortie) avec distinction PDF standard vs stylé
- Commandes EPUB, aperçu en live, batch loop avec résumé d'erreurs
- **examples/skills/pdf-generator.md** : diagramme pipeline de génération (+28 lignes)
- Schéma ASCII SOURCE → Quarto → template → Typst → PDF avec annotations taille de sortie
- **docs/resource-evaluations/2026-02-22-boris-cherny-worktree-tips-reddit.md** : évaluation Reddit/Twitter Boris Cherny (créateur Claude Code) — 5 worktree tips, 40.2K views
- **docs/resource-evaluations/2026-02-22-guillaume-moigneu-worktree-linkedin.md** : évaluation LinkedIn Guillaume Moigneu (Solution Architect @ Upsun) — built-in git worktree support
- **guide/observability.md — 3 nouvelles sections monitoring** (+214 lignes)
- **Activity Monitoring** : audit des actions Claude Code via les JSONL de session — quels fichiers lus, commandes exécutées, URLs fetchées. Requêtes `jq` prêtes à l'emploi. Tableau des patterns sensibles (.env, rm -rf, WebFetch externe)
- **External Monitoring Tools** : tableau comparatif ccusage / claude-code-otel / Akto / MLflow / ccboard avec decision guide et exemples d'install

View file

@ -0,0 +1,170 @@
---
name: security-patcher
description: Apply security patches from security-auditor findings. Requires audit report as input. Always proposes patches for human review — never applies without approval.
model: sonnet
tools: Read, Grep, Glob, Write, Edit
---
# Security Patcher Agent
Apply targeted security fixes based on findings from the `security-auditor` agent.
**Scope**: Patch application only. Requires a security audit report as input. Never audits independently.
> ⚠️ **Separation of responsibilities**: This agent patches, the `security-auditor` detects.
> Always run security-auditor first, then pass findings here.
## Input Contract
Expects a security audit report containing at minimum:
```
Finding: [description]
File: [path]
Line: [number or range]
Severity: CRITICAL | HIGH | MEDIUM
Recommended fix: [description]
```
If no audit report is provided, respond: "No audit report provided. Run the security-auditor agent first."
## Patch Protocol
For each finding in the report:
### 1. Verify the vulnerability
Before patching, confirm the finding is real:
```
Read the file → locate the exact line → confirm the pattern matches the reported vulnerability
```
If the finding cannot be reproduced from the report: skip it, log as "UNVERIFIABLE".
### 2. Understand context
Load surrounding context (±20 lines) to ensure the patch:
- Does not break existing functionality
- Follows the project's coding style and patterns
- Does not introduce new vulnerabilities
Use `Grep` to find similar patterns in the codebase before proposing a fix.
### 3. Propose, do not apply
**Default behavior**: Show the proposed patch for approval, do not write it.
```
PROPOSED PATCH — Severity: CRITICAL
File: src/api/users.ts:45
CURRENT:
const user = await db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);
PROPOSED:
const user = await db.query('SELECT * FROM users WHERE id = $1', [req.params.id]);
Reason: SQL injection via string interpolation. Parameterized query prevents injection.
Risk of change: Low — drop-in replacement, same semantics.
Apply this patch? (yes/no)
```
### 4. Apply only after explicit confirmation
Apply the patch with `Edit` only when the user explicitly confirms (responds "yes", "apply", "go").
If the user responds "no" or "skip": log as "DEFERRED" and move to next finding.
## Patch Scope
### What this agent patches
| Vulnerability type | Patch approach |
|-------------------|----------------|
| SQL injection (string concat) | Parameterized queries |
| XSS (innerHTML assignment) | `textContent` or sanitization |
| Hardcoded secrets | Extract to env var reference |
| MD5/SHA1 for passwords | Replace with bcrypt/argon2 |
| Missing input validation | Add validation at entry point |
| Insecure deserialization | Add type checking |
### What this agent does NOT patch
- Architecture-level vulnerabilities (auth redesign, RBAC changes)
- Anything requiring database migrations
- Third-party library upgrades (report only, user handles `npm audit fix`)
- Test file changes (security fixes in tests only, never in test data)
## Output Format
```markdown
## Security Patch Report
**Date**: [timestamp]
**Source**: [audit report reference]
**Findings processed**: X
**Patches applied**: X
**Patches deferred**: X
**Unverifiable**: X
---
### Applied Patches
#### [SEVERITY] [File:Line] — [Vulnerability type]
- **Before**: [code snippet]
- **After**: [code snippet]
- **Reason**: [why this fixes the issue]
---
### Deferred (awaiting approval)
| Finding | File | Severity | Reason deferred |
|---------|------|----------|----------------|
| SQL injection | src/api.ts:45 | CRITICAL | User requested manual review |
---
### Unverifiable
| Finding | File | Issue |
|---------|------|-------|
| XSS in template | src/views.js:120 | Line not found — may have been fixed |
---
### Not Patched (out of scope)
| Finding | Reason |
|---------|--------|
| Auth redesign needed | Architecture-level, requires manual work |
```
## Safety Rules
1. **Never patch without reading the full file first** — partial context leads to broken patches
2. **Never patch test files' assertions** — only fix actual vulnerable code
3. **One patch per finding** — do not opportunistically fix adjacent issues
4. **Preserve git blame** — only change the exact lines needed
5. **Log every decision** — applied, deferred, or unverifiable
---
## Usage Example
```
# Step 1: Run the auditor
Use the security-auditor agent on src/api/
# Step 2: Pass findings to patcher
Use the security-patcher agent with the following findings:
Finding: SQL injection
File: src/api/users.ts
Line: 45
Severity: CRITICAL
Recommended fix: Use parameterized queries instead of string interpolation
```

View file

@ -0,0 +1,104 @@
#!/bin/bash
# Hook: PreToolUse - Security Gate
# Detects vulnerable code patterns before writing to source files.
#
# Complements dangerous-actions-blocker.sh (system-level ops).
# This hook focuses on APPLICATION security anti-patterns in code.
#
# Place in: .claude/hooks/security-gate.sh
# Register in: .claude/settings.json under PreToolUse event (Write, Edit tools)
#
# Exit 0 = allow, Exit 2 = block (stderr message shown to Claude)
set -e
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty')
# Only check Write and Edit operations on source files
if [[ "$TOOL_NAME" != "Write" && "$TOOL_NAME" != "Edit" ]]; then
exit 0
fi
FILE_PATH=$(echo "$INPUT" | jq -r '.file_path // empty')
# Skip non-source files (tests, docs, configs)
EXTENSION="${FILE_PATH##*.}"
SOURCE_EXTENSIONS="js ts jsx tsx py go java rb php cs"
is_source=false
for ext in $SOURCE_EXTENSIONS; do
[[ "$EXTENSION" == "$ext" ]] && is_source=true && break
done
if [[ "$is_source" == "false" ]]; then
exit 0
fi
# Extract content being written
if [[ "$TOOL_NAME" == "Write" ]]; then
CONTENT=$(echo "$INPUT" | jq -r '.content // empty')
else
# Edit: check both old and new strings
CONTENT=$(echo "$INPUT" | jq -r '.new_string // empty')
fi
# ── PATTERN 1: Hardcoded secrets ──────────────────────────────────────────────
# Detect API keys, passwords, tokens assigned as string literals
if echo "$CONTENT" | grep -qiE '(api[_-]?key|password|secret|token|bearer)\s*=\s*["'"'"'][^"'"'"'$\{][^"'"'"']{8,}["'"'"']'; then
echo "SECURITY-GATE: Potential hardcoded secret detected in $FILE_PATH" >&2
echo "Use environment variables instead: process.env.MY_SECRET or os.getenv('MY_SECRET')" >&2
exit 2
fi
# Known provider key patterns
if echo "$CONTENT" | grep -qE '(sk-[a-zA-Z0-9]{20,}|sk-ant-[a-zA-Z0-9]{20,}|ghp_[a-zA-Z0-9]{36}|AKIA[A-Z0-9]{16}|xox[bps]-[a-zA-Z0-9\-]{20,})'; then
echo "SECURITY-GATE: Provider API key pattern detected in source file $FILE_PATH" >&2
echo "Move to .env and reference via environment variable." >&2
exit 2
fi
# ── PATTERN 2: SQL injection via string interpolation ─────────────────────────
# Detect template literals or string concat in SQL context
if echo "$CONTENT" | grep -qiE '(SELECT|INSERT|UPDATE|DELETE|DROP).{0,60}(\$\{|'"'"'\s*\+\s*|"\s*\+\s*)'; then
echo "SECURITY-GATE: Potential SQL injection pattern in $FILE_PATH" >&2
echo "Use parameterized queries: db.query('SELECT * WHERE id = \$1', [id])" >&2
exit 2
fi
# ── PATTERN 3: XSS via innerHTML / document.write ────────────────────────────
if echo "$CONTENT" | grep -qE '\.innerHTML\s*=\s*[^"'"'"'`]|document\.write\s*\('; then
echo "SECURITY-GATE: Potential XSS pattern in $FILE_PATH" >&2
echo "Use textContent instead of innerHTML, or sanitize input with DOMPurify." >&2
exit 2
fi
# ── PATTERN 4: eval() with dynamic content ───────────────────────────────────
if echo "$CONTENT" | grep -qE 'eval\s*\(\s*[^"'"'"'`]|new\s+Function\s*\(\s*[^"'"'"'`]'; then
echo "SECURITY-GATE: eval() or new Function() with dynamic content in $FILE_PATH" >&2
echo "Avoid eval() with user input. Use JSON.parse() for data, or refactor logic." >&2
exit 2
fi
# ── PATTERN 5: Weak hashing for passwords ────────────────────────────────────
if echo "$CONTENT" | grep -qiE '(md5|sha1|sha256)\s*\(.*password|hashlib\.(md5|sha1)\s*\(.*password'; then
echo "SECURITY-GATE: Weak hash algorithm for password in $FILE_PATH" >&2
echo "Use bcrypt, argon2, or scrypt for password hashing." >&2
exit 2
fi
# ── PATTERN 6: Command injection via exec/shell ───────────────────────────────
if echo "$CONTENT" | grep -qE '(exec|shell_exec|system|popen|subprocess\.call)\s*\([^"'"'"'`].*(\$\{|'"'"'\s*\+|"\s*\+)'; then
echo "SECURITY-GATE: Potential command injection in $FILE_PATH" >&2
echo "Use parameterized subprocess calls, never interpolate user input into shell commands." >&2
exit 2
fi
# ── PATTERN 7: Path traversal via user input ─────────────────────────────────
if echo "$CONTENT" | grep -qE '(readFile|open|fopen|path\.join)\s*\([^)]*req\.(params|query|body)'; then
echo "SECURITY-GATE: Potential path traversal — user input in file path operation ($FILE_PATH)" >&2
echo "Validate and sanitize file paths. Use path.resolve() + check against allowed base directory." >&2
exit 2
fi
# Allow by default
exit 0

View file

@ -703,12 +703,114 @@ echo -e "test\u200Bhidden" | grep -P '[\x{200B}-\x{200D}]'
---
## Part 4: Integration (In Your Daily Workflow)
### 4.1 PR Security Review Workflow
The most high-ROI use of Claude Code for security: systematic review of every PR before merge. Takes 2-3 minutes, catches issues before they reach production.
#### Setup — Add to your PR checklist
```bash
# Run from repo root before merging any PR
git diff main...HEAD > /tmp/pr-diff.txt
```
Then in Claude Code:
```
Review the security implications of this PR diff.
Focus: injection, auth bypass, secrets exposure, insecure deserialization.
File: /tmp/pr-diff.txt
Use the security-auditor agent for the analysis.
```
#### The 3-agent PR security pipeline
For high-stakes PRs (auth changes, payment flows, data access), run in sequence:
```
Step 1 — Threat surface scan:
"Use the security-auditor agent to analyze all changed files in this diff.
Report CRITICAL and HIGH findings only. No fixes."
Step 2 — Data flow trace:
"For each CRITICAL finding from the audit, trace the full data flow:
where does user input enter? where does it reach? what sanitization exists?"
Step 3 — Patch (if findings):
"Use the security-patcher agent with the findings report above.
Propose patches for CRITICAL findings only. Do not apply without my review."
```
#### What to always check in a security PR review
| Change type | Risk | What to look for |
|-------------|------|-----------------|
| New API endpoint | High | Auth check, input validation, rate limiting |
| DB query change | High | Parameterized queries, index exposure |
| Auth logic | Critical | Token validation, session management, privilege escalation |
| File upload | High | MIME type, size limit, path traversal |
| Third-party lib added | Medium | CVE check (`npm audit`, `cargo audit`) |
| Env var added | Medium | Not hardcoded, in `.gitignore`, in `.env.example` |
#### Integration with git hooks
Automate the trigger in `.git/hooks/pre-push`:
```bash
#!/bin/bash
# Pre-push: remind to run security review for auth/payment changes
CHANGED=$(git diff origin/main...HEAD --name-only)
if echo "$CHANGED" | grep -qE "(auth|payment|token|session|password|crypt)"; then
echo "⚠️ Security-sensitive files changed. Run /security-audit before pushing."
echo " Files: $(echo "$CHANGED" | grep -E '(auth|payment|token|session)')"
# Warning only — does not block push
fi
exit 0
```
---
## Claude Code as Security Scanner (Research Preview)
Beyond securing Claude Code itself, Anthropic offers a dedicated vulnerability scanning feature: **Claude Code Security**.
> ⚠️ **Research preview** — Access via waitlist only. Not yet in GA. Details: [claude.com/solutions/claude-code-security](https://claude.com/solutions/claude-code-security)
### What it does
- Scans your entire codebase for vulnerabilities using contextual reasoning (traces data flows cross-files)
- **Adversarial validation**: findings are challenged internally before surfacing to reduce false positives
- Generates patch suggestions that preserve code structure and style
- Requires human review and approval before any fix is applied
### How it differs from the Security Auditor Agent
| | Security Auditor Agent (today) | Claude Code Security (preview) |
|---|---|---|
| **Access** | Available now, any plan | Waitlist only |
| **Scope** | OWASP Top 10, rule-based | Whole codebase, semantic analysis |
| **Patches** | No (reports only) | Yes (with human approval) |
| **Model** | Configurable | Anthropic's most capable models |
### When to use which
- **Now** → Use the [Security Auditor Agent](../examples/agents/security-auditor.md) + [Security Patcher Agent](../examples/agents/security-patcher.md) for full detect-then-patch coverage
- **Now** → Use the [Security Gate Hook](../examples/hooks/bash/security-gate.sh) to block vulnerable patterns at write time
- **Waitlist** → Join the preview for deeper semantic analysis once your team needs it
---
## See Also
- [Data Privacy Guide](./data-privacy.md) — Retention policies, compliance, what data leaves your machine
- [AI Traceability](./ai-traceability.md) — PromptPwnd vulnerability, CI/CD security, attribution policies
- [Security Checklist Skill](../examples/skills/security-checklist.md) — OWASP Top 10 patterns for code review
- [Security Auditor Agent](../examples/agents/security-auditor.md) — Automated vulnerability scanning
- [Security Auditor Agent](../examples/agents/security-auditor.md) — Automated vulnerability detection (read-only)
- [Security Patcher Agent](../examples/agents/security-patcher.md) — Applies patches from audit findings (human approval required)
- [Security Gate Hook](../examples/hooks/bash/security-gate.sh) — Blocks vulnerable code patterns at write time (7 patterns)
- [Ultimate Guide §7.4](./ultimate-guide.md#74-security-hooks) — Hook system basics
- [Ultimate Guide §8.6](./ultimate-guide.md#86-mcp-security) — MCP security overview

View file

@ -602,6 +602,11 @@ deep_dive:
dual_instance_pattern: "Vertical separation (planner vs implementer) - orthogonal to Boris horizontal scaling"
dual_instance_cost: "$100-200/month (vs $500-1K Boris pattern)"
dual_instance_audience: "Solo devs, spec-heavy work, quality > speed"
# Boris Tane Pattern (Annotation Cycle, Feb 2026)
annotation_cycle_pattern: "guide/workflows/plan-driven.md#the-annotation-cycle"
custom_markdown_plans: "guide/workflows/plan-driven.md#why-custom-plans-over-plan"
boris_tane_source: "https://boristane.com/blog/how-i-use-claude-code/"
boris_tane_author: "Boris Tane (Engineering Lead, Cloudflare)"
# External resource: Claude Code team tips (paddo.dev, Feb 2026)
team_tips_paddo: "https://paddo.dev/blog/claude-code-team-tips/"
team_tips_paddo_source: "Boris Cherny thread (x.com/bcherny/status/2017742741636321619)"
@ -855,6 +860,10 @@ deep_dive:
security_audit_command: "examples/commands/security-audit.md" # Full 6-phase security audit (score /100)
security_threat_db: "examples/commands/resources/threat-db.yaml" # Threat intelligence database (authors, skills, CVEs, patterns)
security_update_threat_db: "examples/commands/update-threat-db.md" # /update-threat-db — research & update threat database
security_cc_scanner: "guide/security-hardening.md:776" # Claude Code Security (research preview) — Anthropic native vuln scanner, adversarial validation, patch suggestions
security_patcher_agent: "examples/agents/security-patcher.md" # Agent: applies patches from security-auditor findings, human approval gate, Write/Edit tools
security_gate_hook: "examples/hooks/bash/security-gate.sh" # PreToolUse hook: blocks 7 vuln patterns at write time (SQLi, XSS, hardcoded secrets, eval, weak hash, cmd injection, path traversal)
security_pr_review_workflow: "guide/security-hardening.md:706" # PR security review workflow — 3-agent pipeline, git hook integration
agent_validation_checklist: 3850 # Agent validation section in ultimate-guide.md
git_mcp_guide: "guide/mcp-servers-ecosystem.md:102" # Git MCP server documentation