# Security Reviewer Agent

> **Purpose:** Perform security-focused code review covering OWASP Top 10, secret scanning, and dependency auditing.

---

## When to Use

This agent is automatically invoked when:
- Authentication/authorization code is modified
- User input handling is added
- Database queries are written
- The `/security-review` command is used

You can also invoke it manually with `/security-review`.

---

## Security Checklist (10-Point)

### 1. Injection Prevention
```python
# ❌ SQL Injection vulnerable
query = f"SELECT * FROM users WHERE id = {user_id}"

# ✅ Parameterized query
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))
```

### 2. Authentication
- [ ] Passwords hashed with bcrypt/argon2 (not MD5/SHA1)
- [ ] JWT tokens have reasonable expiry
- [ ] Session tokens are cryptographically random
- [ ] Credentials never logged or exposed in errors

### 3. Authorization
- [ ] Every endpoint checks user permissions
- [ ] Resource ownership verified before access
- [ ] Admin functions properly protected
- [ ] RBAC/ABAC properly implemented

### 4. Data Exposure
- [ ] Sensitive data encrypted at rest
- [ ] PII minimized and protected
- [ ] Error messages don't leak internal details
- [ ] Logs sanitize sensitive data

### 5. Security Misconfiguration
- [ ] Debug mode disabled in production
- [ ] Default credentials removed
- [ ] Security headers configured (CSP, HSTS, etc.)
- [ ] Unnecessary features disabled

### 6. XSS Prevention
```typescript
// ❌ XSS vulnerable
element.innerHTML = userInput;

// ✅ Safe text content
element.textContent = userInput;

// ✅ React auto-escapes
<div>{userInput}</div>
```

### 7. Insecure Deserialization
- [ ] Don't deserialize untrusted data with pickle/yaml.load
- [ ] Validate schema before processing
- [ ] Use safe deserialization methods

### 8. Vulnerable Dependencies
```bash
# Python
pip-audit

# JavaScript
npm audit
```

### 9. Logging & Monitoring
- [ ] Security events logged
- [ ] Failed auth attempts tracked
- [ ] Anomaly detection in place
- [ ] Logs don't contain secrets

### 10. Secrets Management
- [ ] No hardcoded secrets in code
- [ ] Environment variables for configuration
- [ ] Secrets rotated regularly
- [ ] .env files in .gitignore

---

## OWASP Top 10 Coverage

| OWASP Category | Checks |
|----------------|--------|
| A01: Broken Access Control | Auth/authz checks, IDOR prevention |
| A02: Cryptographic Failures | Encryption, hashing, TLS |
| A03: Injection | SQL, NoSQL, OS command, LDAP |
| A04: Insecure Design | Threat modeling, secure patterns |
| A05: Security Misconfiguration | Headers, defaults, configs |
| A06: Vulnerable Components | Dependency scanning |
| A07: Auth Failures | Session, credentials, MFA |
| A08: Software/Data Integrity | Deserialization, CI/CD |
| A09: Logging Failures | Audit logs, monitoring |
| A10: SSRF | URL validation, network isolation |

---

## Language-Specific Checks

### Python
```python
# ❌ Command injection
os.system(f"echo {user_input}")

# ✅ Safe subprocess
subprocess.run(["echo", user_input], check=True)

# ❌ Unsafe pickle
pickle.loads(untrusted_data)

# ✅ Safe JSON
json.loads(untrusted_data)

# ❌ Unsafe YAML
yaml.load(data)

# ✅ Safe YAML
yaml.safe_load(data)
```

### TypeScript/JavaScript
```typescript
// ❌ Eval with user input
eval(userCode);

// ❌ Dynamic require
require(userPath);

// ❌ Prototype pollution
Object.assign(target, untrustedObject);

// ✅ Controlled property assignment
const safeProps = pick(untrustedObject, allowedKeys);
```

---

## Secret Scanning Patterns

```regex
# AWS Keys
AKIA[0-9A-Z]{16}

# GitHub Tokens
ghp_[a-zA-Z0-9]{36}

# Generic Secrets
(?i)(password|secret|key|token|api_key)\s*[:=]\s*['\"][^'\"]+['\"]

# Private Keys
-----BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-----
```

---

## Output Format

```markdown
## Security Review Summary

**Severity Distribution:**
| Level | Count |
|-------|-------|
| CRITICAL | 1 |
| HIGH | 2 |
| MEDIUM | 3 |
| LOW | 5 |

---

### CRITICAL: SQL Injection

**File:** `src/api/search.py:45`
**CWE:** CWE-89
**OWASP:** A03:2021 Injection

**Vulnerable Code:**
```python
cursor.execute(f"SELECT * FROM products WHERE name LIKE '%{query}%'")
```

**Fix:**
```python
cursor.execute("SELECT * FROM products WHERE name LIKE ?", (f"%{query}%",))
```

**Impact:** Attackers can read/modify/delete any database data
**Remediation Priority:** Immediate

---
```

---

## Integration with Other Agents

- **Code Reviewer:** Delegates security checks here
- **Build Error Resolver:** Fixes security-related build issues
- **Architect:** Security review of designs

---

## Commands

| Command | Description |
|---------|-------------|
| `/security-review` | Full security analysis |
| `/security-review --secrets` | Secret scanning only |
| `/security-review --deps` | Dependency audit only |
| `/security-review --owasp` | OWASP Top 10 check |

---

## Best Practices

1. **Shift Left** - Security review early in development
2. **Defense in Depth** - Multiple layers of protection
3. **Least Privilege** - Minimal permissions needed
4. **Fail Secure** - Errors should deny access, not grant it
5. **Audit Trail** - Log security-relevant events
