---
name: review-security
description: Security audit for vulnerabilities, secrets, and unsafe patterns. Use before releases, after adding auth code, or when reviewing third-party integrations.
argument-hint: '[--staged | --unpushed | --changed | --all]'
effort: xhigh
---

# Review Security

Security audit for common vulnerabilities and unsafe patterns.

## Review grading

Use only these finding priorities, in descending order:

- **Critical Issues (Must Fix):** a verified path causes data loss, a security failure, a materially
  wrong operation, or makes a core workflow unusable without reasonable recovery.
- **Improvements (Should Fix):** an ordinary supported workflow demonstrably fails or repeatedly
  imposes substantial friction, or a concrete design defect creates meaningful maintenance cost.
- **Suggestions (Nice to Have):** a worthwhile improvement with small practical impact, including
  optional polish, local simplification, and rare recoverable edge cases.

Grade the demonstrated consequence, realistic reachability, and available recovery against project
priorities. A category, missing convention, hypothetical future problem, or confidence that a claim
is true does not set its priority. Do not assign automatic severity floors or ceilings. Keep
unverified claims in validation gaps, outside the graded finding count; distinguish suggestions
from defects. For plans, trace the consequence if implemented and state the assumptions.

Use the short labels **Must Fix**, **Should Fix**, and **Nice to Have** in summaries and ledgers.
Keep effort, verification status, user-facing change size, and tool/vendor diagnostic ratings
separate. When called by `code-review`, return its requested evidence and impact fields; the parent
owns scoring and final triage. Otherwise apply this rubric directly. Omit empty priority sections.

## Usage

```
/review-security              # Review context-related code
/review-security --staged     # Review staged changes
/review-security --unpushed   # Review files changed across all unpushed commits
/review-security --changed    # Review unstaged changes
/review-security --all        # Full codebase audit (parallel agents)
```

## Scope

| Flag | Scope | Method |
|------|-------|--------|
| (none) | Context-related code | Files from the current conversation context: any files the user has discussed, opened, or that you have read/edited in this session. If no conversation context exists, ask the user to specify files or use `--staged`/`--changed`/`--all`. |
| `--staged` | Staged changes | `git diff --cached --name-only` |
| `--unpushed` | Files changed across unpushed commits | `git diff --name-only $(git rev-list HEAD --not --remotes \| tail -1)^..HEAD` |
| `--changed` | Unstaged changes | `git diff --name-only` |
| `--all` | Full codebase | Glob source files, parallel agents |

`--unpushed` derives its range from `git rev-list HEAD --not --remotes` (oldest unpushed commit's parent → HEAD). If nothing is unpushed, or there is no remote/upstream (or the range walks back to the root commit) so it can't be determined reliably, stop and ask the user to pick another scope.

**Do NOT skip checks:**
- "This code is internal only" -- Internal code gets compromised too
- "This is just a prototype" -- Prototypes become production code
- "I already checked for the obvious issues" -- The non-obvious ones are the dangerous ones

## Gotchas
- Dependency audit commands (`pip-audit`, `safety check`, `bundle audit`, `govulncheck`) must be installed separately. If missing, they silently produce no output rather than erroring.
- `--staged`, `--unpushed`, and `--changed` review the full file content, not just the diff. Pre-existing vulnerabilities in the file are flagged even if the staged/unstaged/unpushed change is unrelated.

## Workflow

1. **Determine scope** based on flags (see Scope table above). For `--all`, map the relevant
   entry points, actors, protected resources, and trust boundaries before assigning checks.
   Keep a compact in-session coverage list; no report files are required.
2. **Review each file** against the Security Checklist below, prioritizing categories in this order:
   1. Injection (OWASP 2021 A03) — highest exploitation likelihood
   2. Sensitive Data Exposure (OWASP 2021 A02) — hardcoded secrets are easy wins
   3. Broken Authentication (OWASP 2021 A07) — auth bugs have outsized impact
   4. Broken Access Control (OWASP 2021 A01) — ownership, role, and tenant enforcement
   5. Security Misconfiguration (OWASP 2021 A05) — config issues are common in PRs
   6. Resource Exhaustion — attacker-controlled resource consumption
   7. Dependency Vulnerabilities — run audit commands last (they take time)
3. **Parallelize** if scope has >5 files: spawn one sub-agent per checklist category, each scanning all files. Merge results and deduplicate.

   Dispatch workers that return findings without editing files. Disable delegation tools where supported; read-only access alone does not prevent delegation. Any coordinating role needs explicit subtasks, a descendant limit, and a stopping condition in its brief.
4. **Check dependencies** using the ecosystem-specific commands in the Dependency Vulnerabilities section
5. **Validate candidates** against the evidence requirements below, checking existing controls
   before accepting a finding. Classify severity using Review grading.
6. **Report findings** grouped by severity using the Output Format below. For `--all`, include
   the coverage summary; a clean finding list does not establish complete coverage.

## Evidence requirements

For each vulnerability, identify the actor and their actual capabilities, controlled input or
action, intended permission or trust boundary, affected resource, and concrete security result.
Cite the source path from entry point through effective controls to the sensitive operation.
Check middleware, shared policy helpers, database policies, and relevant configuration rather
than treating a missing inline check as proof.

State whether verification is source-only or reproduced locally, with exact file/line evidence
and any decisive test result. A complete source trace can establish a defect without a live
exploit. If deployment behavior, provider policy, or another unavailable fact decides the
outcome, put the hypothesis in **Validation gaps**, with the missing fact and a bounded check;
do not assume the control is present or absent, or include it in graded finding counts.
Use dummy identities and records for local checks; a review does not authorize probing live
services or accessing other users' data. Recommend the smallest fix that enforces the boundary.

For `--all`, summarize relevant surfaces and boundaries as **examined**, **partially examined**,
**not examined**, or **not applicable**, with evidence or a reason. Include skipped scanners
and unresolved deployment assumptions. Collect actual coverage from workers; assignment to an
agent alone does not count as examination. Keep this in the response, or return it to the
calling review coordinator, unless the user requested an artifact.

## Security Checklist

> References below use OWASP Top 10 2021 category numbers (A01–A10).

For code examples, grep patterns, false-positive rules, and dependency audit commands, see `references/security-checklist.md`.

### Injection (OWASP A03)

- [ ] No string concatenation in SQL queries (use parameterized queries)
- [ ] No unsanitized user input passed to shell commands
- [ ] No direct HTML insertion from user content (use textContent or a sanitizer)

### Broken Authentication (OWASP A07)

- [ ] Passwords hashed with bcrypt/argon2 (not MD5/SHA1)
- [ ] Rate limiting on login endpoints
- [ ] Session tokens are secure (HttpOnly, Secure, SameSite)
- [ ] No credentials in URLs or logs
- [ ] Account lockout after failed attempts

### Sensitive Data Exposure (OWASP A02)

- [ ] No hardcoded secrets, API keys, or passwords in source code (use environment variables)
- [ ] No sensitive fields (passwords, tokens) written to logs
- [ ] Grep source files for secret patterns — see `references/security-checklist.md` for patterns and false-positive filtering rules

### Broken Access Control (OWASP A01)

- [ ] Read and mutation paths enforce the actor's permission on the requested resource,
  including object ownership, role changes, and tenant boundaries where applicable.
- [ ] Caller-supplied IDs, tenant selectors, and batch items cannot bypass those checks;
  authorization is enforced at a trusted boundary, not solely by UI visibility.
- [ ] Shared middleware, service policies, and database row policies are traced before
  reporting missing enforcement. See the reference for authorization-specific checks.

### Security Misconfiguration (OWASP A05)

- [ ] Debug mode disabled in production
- [ ] No default/test credentials
- [ ] Error messages don't expose internals
- [ ] CORS properly configured (not `*` for sensitive APIs)
- [ ] Security headers set (CSP, X-Frame-Options, etc.)

### Resource Exhaustion

- Trace attacker-controlled payload/read sizes, recursion, queues, and concurrency to effective admission and resource limits. Check existing framework and upstream limits before claiming a missing bound.
- Report the attack path and security consequence. Ordinary workload growth belongs to `review-perf`; operation termination and cancellation belong to `review-correctness`.

### Dependency Vulnerabilities

Run ecosystem-specific audit commands — see `references/security-checklist.md` for commands by ecosystem.

Keep scanner/vendor ratings as evidence. Grade each applicable vulnerability using Review grading after checking the deployed version, reachability, mitigations, and consequence.

## Output Format

For each vulnerability below include actor/input, boundary/resource, demonstrated result,
source trace, and verification method. Keep non-security suggestions separate from defects.

```markdown
## Security Review: {scope}

### Critical Issues (Must Fix)
- {file}:{line} - {vulnerability type}: {description}
  **Fix:** {remediation}

### Improvements (Should Fix)
- {file}:{line} - {issue}
  **Fix:** {remediation}

### Suggestions (Nice to Have)
- {file} - {issue}

### Dependency Vulnerabilities
| Package | Vendor severity | CVE | Fix Version |
|---------|----------|-----|-------------|
| {pkg} | Critical | CVE-XXXX-XXXX | {version} |

### Validation gaps
- {source-grounded hypothesis}: {missing fact}; {bounded validation step}

### Coverage (--all)
| Surface / boundary | Status | Evidence or gap |
|--------------------|--------|-----------------|
| {entry point → protected resource} | {examined / partially examined / not examined / not applicable} | {source paths, checks, or reason} |

```

## Examples

**Staged changes introduce SQL injection:**
> /review-security --staged

Reviews staged files and catches a login handler using string concatenation to build a SQL query with user input. Traces attacker-controlled input to the executed query. If it permits unauthorized data access or mutation, reports Must Fix with a parameterized-query repair; the syntax alone does not establish exploitability.

**Pre-release audit finds hardcoded secret:**
> /review-security --all

Parallel agents scan the full codebase by security category. Finds a hardcoded API key in a config file and a JWT secret committed as a string literal, along with an overly permissive CORS policy allowing all origins.

## Troubleshooting

### False positive on an intentional security pattern
**Solution:** If the flagged code is deliberate (e.g., a test fixture with hardcoded credentials, or a localhost-only CORS wildcard), add a comment like `// SECURITY: intentional - <reason>` so future audits can skip it with context.

### Obfuscated or generated code blocks the audit
**Solution:** Exclude generated files (e.g., `*.min.js`, `dist/`, `generated/`) from the scope and audit only the source inputs. For vendored code, check the upstream project's security advisories rather than scanning the minified output.

## Notes

- Focus on exploitable vulnerabilities, not theoretical risks
- Always provide remediation guidance
- For `--all`, use parallel agents per category for speed
- Check both source code and configuration files
- Dependency checks require package manager files (package.json, requirements.txt, etc.)

Boundary evidence and coverage guidance are informed by
[Cloudflare's security-audit skill](https://github.com/cloudflare/security-audit-skill/blob/main/skills/security-audit/SKILL.md).
