---
name: quality-security-audit
description: "Use when code needs explicit security review — triggered by phrases like 'security review', 'OWASP audit', 'vulnerability scan', 'check for secrets', 'audit the auth', 'crypto review', 'review this for vulns', 'security check', 'is this safe to ship'. Drives OWASP Top 10, secrets scanning, dependency vulnerabilities, and crypto review; integrates Codex + graphify when available for higher-confidence gap detection. Skip for general code quality or performance review (use quality-code-review instead) — security-audit depth costs token budget that's wasted on non-sensitive surfaces."
---

# Security Audit

## Overview

Perform a focused security audit covering the most critical vulnerability categories. Every finding includes a realistic exploit scenario -- not just "best practice" warnings.

**Core principle:** If you cannot describe how an attacker would exploit it, it is not a real finding. If you can describe the exploit, it must be fixed.

**Announce at start:** "I'm using the quality-security-audit skill to audit this code for security vulnerabilities."

## When to Use

- Before deployment to production
- When `quality-code-review` escalates to security audit (High/Critical risk)
- On-demand when the user requests a security review
- After adding authentication, authorization, payment, or data handling code
- When integrating third-party packages or services

**Not for:**
- General code quality (that is quality-code-review)
- Performance issues (that is quality-code-review performance section)
- Non-security configuration issues

## When to load references

- **`references/owasp-checks.md`** — full OWASP Top 10 (A01-A10): per-category check lists and realistic exploit scenarios. Load this when starting Phase 1.
- **`references/audit-report-template.md`** — canonical markdown structure for the audit report, plus the finding format used in every phase. Load this when writing the report or recording any finding.

## Agent Dispatch

Dispatch the **security-reviewer** subagent for the audit. It runs the **depth pass on top of the safety floor** — threat modeling, supply chain, auth-model defensibility, multi-tenant isolation, crypto primitives, CSRF/CORS/headers, logging posture. The per-line safety floor (SQL injection on a single query, missing auth check on a single controller, secret hardcoded in a file) is `code-reviewer`'s job and is assumed to have run via `quality-code-review` already; if it has not, run it first.

The security-reviewer determines the appropriate depth based on the scope of changes.

## The Audit Process

### Phase 0: Codex Mode Check

Run the Codex consent flow from `protocols/codex.md` before proceeding.

- **Takeover selected:** Dispatch Codex `adversarial-review` to execute the full OWASP audit and all 6 phases. Claude reviews Codex's findings at the end.
- **Verify selected** or **Skip / Codex unavailable:** Proceed with Phases 1-6 below. If Verify was selected, the Codex Adversarial Review step at the end will dispatch Codex to check Claude's findings.

### Phase 1: OWASP Top 10 — Depth Check

Systematically check the code against each OWASP Top 10 category **at the depth level**. Load **`references/owasp-checks.md`** for the full per-category check lists and exploit scenarios.

Per-line ship-blockers in these categories (a single concatenated query, a single missing auth check, a single hardcoded secret) belong to `code-reviewer` and are assumed handled. The audit asks the **system-level** question for each category.

| ID | Category | Depth question (system-level) |
|---|---|---|
| A01 | Broken Access Control | Is multi-tenant isolation enforced at the data layer? Is the IDOR posture systematic, not just one fix? Is CORS scoped, not `*` with credentials? |
| A02 | Cryptographic Failures | Are algorithm choices defensible (hash, RNG, TLS)? Key storage and rotation? IV / nonce uniqueness? |
| A03 | Injection | Is input validated at every trust boundary (not just the outer one)? Are parsers (XML, file, queue) hardened? |
| A04 | Insecure Design | Rate limiting, business-logic abuse paths, defense in depth |
| A05 | Security Misconfiguration | CSP / HSTS / X-Frame-Options / Referrer-Policy / X-Content-Type-Options coverage; debug surfaces; default credentials |
| A06 | Vulnerable Components | CVEs (run `npm audit` / `pip audit` / `govulncheck` / `cargo audit`); typosquatting; unpinned versions; postinstall scripts |
| A07 | Auth Failures | Hashing algorithm + work factor; session rotation policy; JWT validation (alg/exp/iss/aud); brute-force defense; account recovery |
| A08 | Data Integrity Failures | Unsigned updates; untrusted deserialization (pickle, ObjectInputStream, eval-equivalents) |
| A09 | Logging & Monitoring Failures | Auth events logged; PII stripped from logs; log injection defenses; alerting on attack-pattern failures |
| A10 | SSRF | User-controlled URL surfaces across the system; internal network and cloud metadata exposure |

For every finding at MEDIUM or above, include a realistic exploit scenario using the finding format in `references/audit-report-template.md`.

### Phase 2: Secrets Scanning — Codebase-Wide Sweep

This is the **depth pass**, not a duplicate of `code-reviewer`'s per-file check. `code-reviewer` flags a single hardcoded secret on a specific changed line; this phase sweeps the entire codebase (current + historical via `git log -S`) for systemic exposure: secrets that pre-date this branch, secrets in seed / test fixtures / docker-compose / CI config that the per-diff review can't see, credentialed URLs in committed configs, and patterns indicating leaked keys across branches.

**Search patterns:**

```
# API keys
grep -rn "api[_-]?key.*=.*['\"][a-zA-Z0-9]" --include="*.ts" --include="*.js" --include="*.py"

# AWS credentials
grep -rn "AKIA[0-9A-Z]{16}" .
grep -rn "aws[_-]?secret" --include="*.ts" --include="*.js" --include="*.py" --include="*.env*"

# JWT secrets
grep -rn "jwt[_-]?secret.*=.*['\"]" .

# Generic passwords
grep -rn "password.*=.*['\"][^$]" --include="*.ts" --include="*.js" --include="*.py"

# Private keys
grep -rn "BEGIN.*PRIVATE KEY" .

# Connection strings with credentials
grep -rn "://[^/]*:.*@" --include="*.ts" --include="*.js" --include="*.py"
```

**Check these files specifically:**
- All `.env` files (should not be committed)
- Configuration files (config.ts, settings.py, etc.)
- Test fixtures and seed data
- Docker-compose files
- CI/CD configuration files
- README and documentation

### Phase 3: Dependency Vulnerabilities

Run automated tools and manually review results.

```bash
# Step 1: Run audit tool
npm audit --json > audit-results.json
# or: pip audit --format json > audit-results.json

# Step 2: Analyze severity distribution
# Critical: Patch immediately
# High: Patch before deployment
# Medium: Patch within sprint
# Low: Track and patch in maintenance cycle
```

Record each vulnerability using the finding format in `references/audit-report-template.md`, including a BLOCKED line that notes whether anything prevents the upgrade.

### Phase 4: Supply Chain Risks

Review dependencies for supply chain attack vectors.

**Check for:**
- **Typosquatting:** Package names similar to popular packages (e.g., `lodashe` instead of `lodash`)
- **Unpinned versions:** Using `^` or `*` instead of exact versions in production dependencies
- **Very new packages:** Published within last 30 days with no established track record
- **Single maintainer packages:** Bus factor of 1 for critical dependencies
- **Excessive permissions:** Packages requesting unnecessary filesystem or network access
- **Install scripts:** Packages with postinstall scripts that run arbitrary code

```bash
# Check for install scripts
npm ls --json | jq '.dependencies | to_entries[] | select(.value.scripts.postinstall)'

# Check package age and download counts
npm view <package> time.created
npm view <package> --json | jq '.dist-tags, .maintainers'
```

### Phase 5: Auth/Authz Boundary Verification — System-Level Map

`code-reviewer` (Pass 1) checks each individual endpoint for a missing auth guard. This phase asks the **system-level question**: is the boundary model coherent across the application — IDOR posture, owner-vs-admin distinction at the data layer, expired/invalid token handling, cross-tenant access patterns.

**Process:**

1. **List all endpoints/routes** with their required auth level
2. **Verify each endpoint** has appropriate middleware/guards
3. **Test boundary conditions:**
   - Unauthenticated access to protected endpoints
   - Authenticated user accessing another user's resources
   - Regular user accessing admin endpoints
   - Expired token handling
   - Invalid token handling

```markdown
| Endpoint | Required Auth | Actual Auth | IDOR Check | Status |
|----------|--------------|-------------|------------|--------|
| GET /api/users | Admin | Admin middleware | N/A | PASS |
| GET /api/users/:id | Owner or Admin | Auth middleware only | FAIL - no owner check | FAIL |
| POST /api/users | Public | None | N/A | PASS |
| PUT /api/users/:id | Owner | Auth middleware only | FAIL - no owner check | FAIL |
| DELETE /api/users/:id | Admin | Auth middleware | N/A | PASS |
```

### Phase 6: Data Exposure Review

Check for unintentional data exposure.

**Check these locations:**
- **Log output:** Search for PII (email, phone, address, SSN) in log statements
- **Error messages:** Ensure errors do not expose stack traces, SQL queries, or internal paths
- **API responses:** Verify responses do not include fields not in the API contract (e.g., password hash, internal IDs)
- **Client-side bundles:** Check that server-only data is not included in frontend builds
- **Debug endpoints:** Ensure no debug/test endpoints exist in production code
- **Database backups:** Verify backup strategy does not expose data

## Audit Report

Write the report following the structure in **`references/audit-report-template.md`**. The template covers metadata, executive summary, findings (by severity), dependency audit, supply chain review, auth boundary map, secrets scan, recommendations, and the quality gate.

## Codex Adversarial Review

After completing all 6 phases, check the mode recorded at Phase 0. If **Verify** was selected, dispatch `adversarial-review` to find authorization gaps, cross-package permission mismatches, and security primitives defined but not enforced. Merge Claude + Codex findings in the final report. If **Takeover** was selected, skip this step (Codex already ran the audit). If **Skip**, do nothing. Do NOT re-run the consent flow. See **Codex Integration** section below for full details.

## Severity Classification

| Severity | Criteria | Response Time |
|----------|----------|---------------|
| CRITICAL | Active exploitation possible, data breach risk | Fix before any deployment |
| HIGH | Exploitable with moderate effort, significant impact | Fix before production deployment |
| MEDIUM | Exploitable with significant effort, limited impact | Fix within current sprint |
| LOW | Theoretical risk, minimal impact | Track and fix in maintenance |
| INFO | Best practice recommendation, no exploit scenario | Optional improvement |

**Rule:** INFO-level findings with no exploit scenario are acceptable. MEDIUM and above MUST have a realistic exploit scenario.

## Common Mistakes

| Mistake | Fix |
|---------|-----|
| "Best practice" warnings without exploit | Every finding needs a realistic exploit scenario |
| Skipping dependency audit | Always run the automated audit tool |
| Only checking new code | Audit the full attack surface, not just changes |
| Missing auth boundary verification | Systematically map and verify every endpoint |
| Not checking logs for PII | Logs are a common data leak vector |
| Accepting "we'll fix it later" for critical findings | Critical findings block deployment. Period. |
| Not checking supply chain | Dependency attacks are increasingly common |

## Red Flags

**Never:**
- Report findings without exploit scenarios (except INFO level)
- Skip any of the 6 phases
- Allow deployment with CRITICAL findings
- Ignore dependency vulnerabilities
- Accept "we'll add auth later" for protected endpoints

**Always:**
- Check all OWASP Top 10 categories
- Run automated dependency audit
- Verify auth boundaries systematically
- Check for secrets in code
- Provide realistic exploit scenarios
- Prioritize findings by severity
- Include fix recommendations

## I/O Contract

| Field | Value |
|---|---|
| **Requires** | Implementation code, dependency manifests (package.json, requirements.txt, go.mod), deployment configuration (if applicable) |
| **Produces** | Security audit report (`.forge/work/{type}/{name}/security-audit.md` or in conversation) |
| **Returns to** | `quality-code-review` (escalation response — findings returned to caller for fixing) |
| **Feeds into** | `deliver-deploy` (security gate) |
| **Updates manifest** | `gates-passed.security-audit: true/false` |

## Graphify Context (Optional)

**Protocol:** `protocols/graphify.md` | **Guard:** Run the status check from the protocol before Phase 1.

Security audits benefit heavily from graph context — community boundaries reveal cross-package permission patterns, and dependency tracing exposes auth chain gaps.

**How graph data maps to this skill:**
- **God nodes** → highest-risk components, audit these first
- **Community boundaries** → cross-community edges reveal permission chain gaps
- **EXTRACTED edges** → trusted dependency paths for auth flow verification
- **INFERRED edges** → flag as potential hidden auth bypasses

**CLI queries** (if graph exists and CLI available):
- `graphify path "auth" "billing" --graph graphify-out/graph.json` — trace permission chains across packages
- `graphify path "middleware" "routes" --graph graphify-out/graph.json` — verify auth middleware covers all route groups
- `graphify query "what routes lack authentication" --budget 1500 --graph graphify-out/graph.json` — find unprotected endpoints

**Codex bridge:** Pass graph community boundaries and permission chain traces to the Codex verify step below. Graph signals materially improve Codex's recall on cross-package authorization gaps.

---

## Codex Integration

**Modes:** Verify or Takeover | **Protocol:** `protocols/codex.md` | **Command:** `adversarial-review`

- **Verify:** Claude runs the OWASP audit, Codex adversarial-reviews for gaps.
- **Takeover:** Codex runs the full security audit, Claude reviews findings.

**When:** After Claude's security-reviewer completes the OWASP audit (sequential, not parallel). This is the highest-value Codex integration point — the Codex + graph combination consistently surfaces authorization gaps that the primary security-reviewer misses — including cross-package permission mismatches and unused security primitives.

**Invocation:**
```bash
node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" adversarial-review --scope branch "authorization gaps, permission mismatches across packages, security primitives defined but not enforced. Find what the existing review missed."
```

**What Codex reviews:**
- Authorization gaps (weaker checks on some routes vs others)
- Cross-package permission mismatches
- Unused security primitives (defined but unenforced limits, uncalled validators)
- Secrets or credentials in code

**Presentation:** Claude security findings + Codex security findings + disagreements. User resolves before gate passes.

---

## Integration

**Called by:**
- `quality-code-review` (escalation from High/Critical risk classification)
- `/feature` command (before deployment, if project profile requires it)
- On-demand by user request

**Pairs with:**
- `quality-code-review` (reviews feed back for fixing)
- `deliver-deploy` (security audit is a deployment gate)
- `build-tdd` (security fixes follow TDD cycle)
