Api audit

From cwinvestments/memstack · View interactive version

Api audit is an AI agent skill from the GitHub repository cwinvestments/memstack. Use this skill when the user says 'audit API', 'check API security', 'API routes security', 'endpoint audit', 'check my routes', or needs to verify API route protection. Reviews API endpoints for authentication, authorization, and input validation gaps. Do NOT use for frontend security headers or de

How to use this skill

Skill file

đŸ›Ąī¸ API Audit: Checking API Route Security...

Audit Next.js API routes for authentication, authorization, validation, and common vulnerabilities.

Activation

When this skill activates, output:

đŸ›Ąī¸ API Audit: Checking API Route Security...

Then execute the protocol below.

Context Guard

| Context | Status |

|---------|--------|

| User asks to audit/check API routes | ACTIVE: full audit |

| User mentions API security | ACTIVE: full audit |

| User asks about endpoint protection | ACTIVE: full audit |

| User is writing a new API route | DORMANT: let them finish first |

| Non-Next.js project | DORMANT, not applicable (adapt if Express/Fastify detected) |

Protocol

Step 1: Discover API Routes

Find all API route files in the project:

  1. App Router (Next.js 13+):

```bash

find . -path "/app/api//route.ts" -o -path "/app/api//route.js"

```

Each file exports named functions: GET, POST, PUT, PATCH, DELETE.

  1. Pages Router (legacy):

```bash

find . -path "/pages/api/.ts" -o -path "/pages/api/.js"

```

Each file exports a default handler.

  1. Middleware:

```bash

find . -name "middleware.ts" -o -name "middleware.js" | head -5

```

Check if global auth middleware exists (reduces per-route auth requirements).

  1. Server Actions (Next.js 14+):

```bash

grep -r "'use server'" --include=".ts" --include=".tsx" -l

```

Server actions are also attack surface: treat as API routes. For each server action function, verify it performs authentication before accessing data. Server actions are callable from any client component and receive no automatic auth: they are functionally identical to unauthenticated POST endpoints unless the function explicitly calls getSession(), getAuthContext(), or equivalent.

Compile a list of all routes with their HTTP methods and file paths.

Step 2: Check Authentication (Check 1)

For each route, determine if it verifies the caller is authenticated:

Search for auth patterns in each route file:

Classify each route:

| Status | Meaning |

|--------|---------|

| ✅ Authenticated | Auth check found before data access |

| 🔴 No Auth | No authentication pattern detected |

| â„šī¸ Public | Route is intentionally public (webhooks, health checks, public data) |

| âš ī¸ Middleware-only | Auth handled by middleware, verify matcher covers this route |

Flag as CRITICAL if a route performs database writes or returns user-specific data with no auth.

Known public route patterns (classify as â„šī¸ INFO, not CRITICAL):

Step 3: Check Authorization (Check 2)

For authenticated routes, verify they check what the user can access:

Search for authorization patterns:

Flag as WARNING if:

Pattern to enforce:

// BAD, trusts client-provided org ID
const { orgId } = await req.json();
const data = await db.from('documents').select().eq('org_id', orgId);

// GOOD, derives org from authenticated session
const { orgId } = await getAuthContext(req);
const data = await db.from('documents').select().eq('org_id', orgId);

Step 4: Check Input Validation (Check 3)

For routes that accept request body or query params:

Search for validation patterns:

Flag as WARNING if:

Flag as CRITICAL if:

Step 5: Check Rate Limiting (Check 4)

For public-facing routes:

Search for rate limiting patterns:

Flag as WARNING if:

Step 5b: Check Request Size Limits (Check 4b)

For POST/PUT/PATCH routes that accept request bodies:

Search for size enforcement patterns:

Flag as WARNING if:

Note: Next.js App Router does NOT enforce a default body size limit on route handlers. Unlike the Pages Router (which defaults to 1MB via bodyParser), App Router passes the raw request through. Projects must enforce limits explicitly.

Correct pattern:

// Check Content-Length before parsing
const contentLength = parseInt(request.headers.get('content-length') || '0');
if (contentLength > 1_000_000) { // 1MB
  return NextResponse.json({ error: 'Request too large' }, { status: 413 });
}
const body = await request.json();

Step 5c: Check Idempotency Keys (Check 4c)

For routes that create payments, charges, transfers, or financial transactions:

Search for idempotency patterns:

Identify payment mutation routes:

Search for routes that call:

Flag as WARNING if:

Correct pattern:

// Stripe, pass idempotency key from client or generate deterministically
const session = await stripe.checkout.sessions.create(
  { ... },
  { idempotencyKey: `order-${orderId}-${timestamp}` }
);

Step 6: Check SQL Injection (Check 5)

Search for dangerous query patterns:

Safe patterns (do not flag):

Step 7: Check Data Exposure (Check 6)

Search for sensitive data in responses:

Fields that should never appear in API responses:

password, password_hash, hashed_password, secret, token, refresh_token, api_key, private_key, ssn, credit_card

Search each route file for these field names, then check if they appear in return/response paths.

Step 8: Check CORS Configuration (Check 7)

Search for CORS patterns:

Check next.config.js or next.config.mjs:

grep -A5 "Access-Control\|headers\(\)" next.config.*

Step 9: Check Error Handling (Check 8)

Search for error patterns in each route:

Correct pattern:

catch (error) {
  console.error('Route /api/items failed:', error);
  return NextResponse.json(
    { error: 'Internal server error' },
    { status: 500 }
  );
}

Step 10: Check Webhook & Special Routes (Check 9)

For webhook routes (/api/webhooks/*):

For file upload routes:

For DELETE routes:

Step 11: Generate Report

đŸ›Ąī¸ API Security Audit Report
Project: <project-name>
Routes found: <count>
Server actions: <count>
Global middleware auth: <yes/no>

## Route Audit

| Route | Method | Auth | Authz | Validation | Risk | Issues |
|-------|--------|------|-------|------------|------|--------|
| /api/users | GET | ✅ | ✅ | ✅ | ✅ OK | none |
| /api/users | POST | ✅ | ✅ | 🔴 | âš ī¸ WARN | No input validation |
| /api/items/[id] | DELETE | 🔴 | 🔴 | none | 🔴 CRIT | No auth, no ownership check |
| /api/webhooks/stripe | POST | â„šī¸ | none | none | ✅ OK | Signature verified |
| /api/admin/users | GET | ✅ | âš ī¸ | ✅ | âš ī¸ WARN | No role check for admin route |

## Critical Issues
1. **DELETE /api/items/[id]**: No authentication. Any request can delete any item.
   → Fix: Add `getAuthContext(req)` and verify `item.user_id === user.id` before deleting.

2. **POST /api/upload**: No file size limit. Server vulnerable to resource exhaustion.
   → Fix: Add size limit config or check `Content-Length` header.

## Warnings
1. **POST /api/users**: Request body parsed without schema validation.
   → Fix: Add Zod schema and parse before processing.

2. **GET /api/admin/users**: Authenticated but no admin role verification.
   → Fix: Add role check before returning data.

## Info
1. **Supabase RLS active**: Authorization may be handled at database layer for some routes.
   Verify RLS policies cover the same access patterns. Run `rls-checker` for full RLS audit.

## Summary
- 🔴 Critical: <count>
- âš ī¸ Warning: <count>
- â„šī¸ Info: <count>
- ✅ OK: <count>
- Total routes: <count>

## Checklist
- [ ] All non-public routes authenticate callers
- [ ] All data-access routes verify ownership/org membership
- [ ] All POST/PUT/PATCH routes validate input with schema
- [ ] Login/register routes have rate limiting
- [ ] Webhook routes verify signatures
- [ ] No raw SQL with user input
- [ ] API responses exclude sensitive fields
- [ ] Error responses don't leak stack traces
- [ ] CORS configured for specific origins, not wildcard
- [ ] POST/PUT/PATCH routes enforce request body size limits
- [ ] Payment-creating routes use idempotency keys
- [ ] Server actions verify auth before data access

Step 12: Suggest Fixes

For each CRITICAL and WARNING issue, provide:

  1. The exact code fix with file path and line number
  2. Any new dependencies needed (e.g., @upstash/ratelimit for rate limiting)
  3. Whether the fix requires changes to other files (middleware, types, etc.)

Offer to apply fixes directly if the user approves.

Risk Levels

| Level | Meaning | Action |

|-------|---------|--------|

| 🔴 CRITICAL | Active vulnerability exploitable without auth | Fix immediately |

| âš ī¸ WARNING | Missing defense layer or weak pattern | Fix before production |

| â„šī¸ INFO | Acceptable pattern worth verifying | Review and confirm intentional |

| ✅ OK | Properly secured | No action needed |

Related Skills

Level History

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.