# AI-Driven Security Auditing

> Using AI coding agents to perform systematic security audits of your own codebase. Find vulnerabilities before attackers do.

## When to Use

- Before any production deployment
- After adding new services or endpoints
- Periodically (monthly/quarterly)
- After integrating new LLM/AI features

## The Pattern

Ask the AI agent to perform a **structured static analysis** across your codebase, organized by security domain.

## The Audit Prompt

```
Perform a security audit of this codebase. Check the following domains:

1. **AI/LLM Integration Points** — List every LLM call, check for prompt injection, output validation
2. **Authentication** — JWT handling, token storage, session management
3. **Authorization** — Route protection, role enforcement, ownership checks
4. **Input Validation** — Zod/schema coverage on all endpoints
5. **Secrets Management** — Hardcoded credentials, env var handling
6. **CORS & Headers** — CORS policy, security headers, CSRF protection
7. **Infrastructure** — Docker security, exposed ports, default credentials
8. **Data Isolation** — Multi-tenancy, cache key isolation, query scoping

For each finding, provide:
- Severity (Critical/High/Medium/Low/Info)
- Location (file:line)
- OWASP mapping (ASVS, LLM Top 10, or MITRE ATLAS)
- Attack scenario
- Remediation steps

Do NOT make changes — report only.
```

## Audit Report Structure

```markdown
# Security Audit Report

## Executive Summary

- Overall risk: MEDIUM-HIGH
- Critical: 5, High: 8, Medium: 9, Low: 6, Info: 5

## Existing Controls (what's already good)

| Control                         | Status      | Location          |
| ------------------------------- | ----------- | ----------------- |
| Zod validation on all endpoints | Implemented | All routes        |
| Pre-commit secret scanning      | Implemented | .husky/pre-commit |
| JWT with issuer binding         | Implemented | auth module       |

## Findings by Severity

### F-001: [Title] — [Status]

| Field           | Value                         |
| --------------- | ----------------------------- |
| Severity        | Critical                      |
| Location        | file.ts:42                    |
| OWASP           | LLM01:2025 — Prompt Injection |
| Description     | ...                           |
| Attack scenario | ...                           |
| Remediation     | ...                           |
```

## Key Audit Domains

### 1. LLM/AI Security (OWASP LLM Top 10)

| Check                     | What to look for                                        |
| ------------------------- | ------------------------------------------------------- |
| Prompt injection          | User input directly in prompts without delimiters       |
| Output validation         | JSON.parse without schema validation                    |
| Sensitive data in prompts | PII, credentials passed to LLM                          |
| Excessive agency          | LLM responses triggering actions (URL fetch, DB writes) |
| Model denial of service   | Unbounded input length to LLM                           |
| Task hijacking            | User-controlled task prompts overriding system behavior |

### 2. Authentication & Session

| Check               | What to look for                                  |
| ------------------- | ------------------------------------------------- |
| JWT storage         | localStorage (XSS-vulnerable) vs httpOnly cookies |
| Token validation    | Missing issuer/audience checks                    |
| Shared signing keys | Same JWT_SECRET across all services               |
| Missing auth        | Endpoints without authentication middleware       |
| Refresh token flow  | Missing or broken token rotation                  |

### 3. Infrastructure

| Check               | What to look for                        |
| ------------------- | --------------------------------------- |
| Default credentials | Grafana admin/admin, database passwords |
| Exposed ports       | Internal services accessible externally |
| Docker as root      | Missing USER directive in Dockerfile    |
| Insecure dashboards | Traefik/admin panels without auth       |
| CORS wildcards      | `origin: true` allowing any domain      |

### 4. Data & Multi-Tenancy

| Check               | What to look for                               |
| ------------------- | ---------------------------------------------- |
| Missing productId   | Cosmos documents without tenant isolation      |
| Cache pollution     | Shared cache keys across users                 |
| SSRF                | Server-side URL fetching of user-provided URLs |
| SQL/NoSQL injection | Unsanitized query parameters                   |

## Real-World Findings

From auditing a 5-repo ecosystem:

| Finding                                        | Severity | Root Cause                                      |
| ---------------------------------------------- | -------- | ----------------------------------------------- |
| SSRF via URL fetch in triage                   | Critical | User URL fetched server-side without validation |
| Grafana default password in docker-compose.yml | Critical | Credentials hardcoded in version control        |
| 33 API routes with no auth                     | Critical | MindLyst web API had no authentication at all   |
| JWT in localStorage                            | Critical | XSS can exfiltrate admin tokens                 |
| LLM output not validated                       | High     | JSON.parse without Zod schema validation        |
| No prompt injection defense                    | High     | User content directly interpolated into prompts |
| Shared JWT_SECRET                              | High     | One compromised service exposes all services    |
| Docker containers run as root                  | Medium   | Missing USER directive                          |
| In-memory rate limiting                        | Medium   | Per-instance, not distributed                   |

## Compliance Mapping

Map findings to standards your org cares about:

| Standard         | Use For                  |
| ---------------- | ------------------------ |
| OWASP ASVS 4.0   | Web application security |
| OWASP LLM Top 10 | AI/LLM-specific risks    |
| MITRE ATLAS      | AI attack techniques     |
| NIST AI RMF      | AI risk management       |
| ISO 42001        | AI management systems    |
| SOC 2            | Organizational controls  |

## Anti-Patterns

- **One-time audit** — Security degrades continuously; audit regularly
- **Only auditing new code** — Old code has the most vulnerabilities
- **Not tracking findings** — Use a table with status (Open/Partial/Resolved)
- **Fixing everything at once** — Prioritize by severity and attack likelihood
- **Auditing without remediation** — An audit that produces a report and nothing else is waste

## Automation

After your first manual audit, automate recurring checks:

```bash
# Quick security check script
#!/bin/bash
echo "=== Secret Scan ==="
bash scripts/secret-scan-repo.sh

echo "=== Dependency Audit ==="
npm audit --production
pip-audit  # Python

echo "=== Hardcoded Credentials ==="
grep -rn 'password.*=.*["\x27]' src/ --include='*.ts' --include='*.py' || echo "None found"

echo "=== Missing Auth Middleware ==="
grep -rn 'server\.\(get\|post\|put\|delete\)' src/modules/ --include='*.ts' | grep -v 'preHandler.*auth' || echo "All routes have auth"
```

## Related Skills

- [09 — Secret Scanning Guardrails](./09-secret-scanning.md)
- [10 — LLM Abuse Controls](./10-llm-abuse-controls.md)
- [12 — Pre-Release Quality Gates](./12-quality-gates.md)
