| description | Fuzz test APIs with malformed inputs and edge cases |
| shortcut | fuzz |
API Fuzzer
Automated fuzz testing for REST APIs to discover vulnerabilities, crashes, and unexpected behavior through malformed inputs, boundary values, and random payloads. This command generates comprehensive fuzz test suites targeting injection attacks, input validation failures, and edge cases.
Design Decisions
Why fuzz testing matters:
- Security: Discovers SQL injection, XSS, command injection vulnerabilities
- Robustness: Finds crashes from unexpected inputs before users do
- Edge cases: Uncovers boundary conditions developers didn't consider
- Compliance: Validates input sanitization meets security standards
Alternatives considered:
- Manual testing: Too slow, can't cover mutation space
- Property-based testing: Good for unit tests, less suited for API integration
- Penetration testing tools: Expensive, requires security expertise
- Static analysis: Misses runtime-only issues
This approach balances: Automation, coverage, security focus, and integration with CI/CD.
When to Use
Use API fuzzing when:
- Testing security-critical APIs (auth, payment, admin endpoints)
- Validating input sanitization and validation logic
- Finding edge cases before production incidents
- Meeting security compliance requirements (PCI-DSS, SOC 2)
- Testing third-party API integration error handling
- Preparing for penetration testing or security audits
Don't use when:
- API has no user input (static data endpoints)
- Building proof-of-concept with no security requirements
- Input validation is already exhaustively tested
- Time-sensitive release without CI/CD integration
Prerequisites
- Existing REST API with endpoints to test
- Node.js 16+ or Python 3.8+ for fuzzing scripts
- API documentation (OpenAPI/Swagger or manual endpoint list)
- (Optional) Authentication credentials or test accounts
- (Optional) CI/CD pipeline for automated fuzzing
- (Optional) Security monitoring tools (SIEM, IDS)
Process
-
Identify Attack Surface
- List all API endpoints accepting user input
- Identify input types (strings, numbers, JSON, files)
- Prioritize high-risk endpoints (auth, admin, payment)
-
Generate Fuzz Inputs
- Malformed data (null, undefined, empty, overflow)
- Injection payloads (SQL, XSS, command injection)
- Boundary values (max int, negative, infinity)
- Type confusion (string as int, object as array)
-
Execute Fuzz Tests
- Send fuzz inputs to all endpoints
- Monitor responses for crashes, 500 errors, timeouts
- Capture stack traces and error details
-
Analyze Results
- Categorize vulnerabilities by severity (critical, high, medium)
- Create reproducible test cases for failures
- Generate security report with findings
-
Remediate and Retest
- Fix discovered vulnerabilities
- Add regression tests for fixed issues
- Rerun fuzzer to verify fixes
Output Format
Jest Fuzz Test Suite (Node.js)
const axios = require('axios');
const API_BASE = process.env.API_URL || 'http://localhost:3000';
const fuzzInputs = {
strings: [
'',
null,
undefined,
' ',
'A'.repeat(10000),
'A'.repeat(1000000),
'<script>alert(1)</script>',
'<img src=x onerror=alert(1)>',
'${7*7}',
'{{7*7}}',
'\x00',
'\n\r\t',
'../../etc/passwd',
'../../../etc/passwd',
'\\x41\\x42\\x43',
],
sqlInjection: [
"' OR '1'='1",
"' OR '1'='1' --",
,
,
,
,
,
,
],
: [
,
-,
,
,
-,
,
-,
,
.,
.,
.,
.,
,
],
: [
,
,
,
,
,
,
,
,
],
: [
{},
[],
{ : { : } },
{ : { : { : } } },
[[[[[]]]]]],
().(),
],
: [
,
,
,
,
,
,
,
],
};
(, {
(, {
(, () => {
( input fuzzInputs.) {
{
response = axios.(, {
: input,
: ,
}, { : });
(response.)..();
(response.).();
(response. >= ) {
(response.).();
}
} (error) {
(error. !== && error. !== ) {
error;
}
}
}
});
(, () => {
( payload fuzzInputs.) {
response = axios.(, {
: payload,
: payload,
}, { : });
(response.)..();
(response.).();
(response..) {
(response...())..();
}
}
});
(, () => {
( input fuzzInputs.) {
response = axios.(, {
: input,
: ,
: ,
}, { : });
(response.)..();
(input < || input > ) {
(response.).();
}
}
});
(, () => {
( input fuzzInputs.) {
response = axios.(, {
: input,
: ,
: ,
}, { : });
(response.)..();
}
});
});
(, {
(, () => {
idInputs = [
...fuzzInputs.,
...fuzzInputs.,
...fuzzInputs.,
];
( input idInputs) {
response = axios.(
,
{ : }
);
(response.)..();
([, ]).(response.);
}
});
});
(, {
(, () => {
( input fuzzInputs.) {
response = axios.(, {
: { : input },
: ,
});
(response.)..();
}
});
(, () => {
( payload fuzzInputs.) {
response = axios.(, {
: { : payload },
: ,
});
(response.)..();
(response. === ) {
(response..).();
}
}
});
});
});
Python REST-Assured Fuzzer
import pytest
import requests
from typing import Any, List
import string
import random
API_BASE = "http://localhost:3000"
class FuzzInputGenerator:
"""Generate various fuzz inputs for API testing"""
@staticmethod
def string_mutations() -> List[Any]:
return [
"",
None,
" ",
"A" * 10000,
"<script>alert(1)</script>",
"${7*7}",
"../../etc/passwd",
"\x00",
]
@staticmethod
def sql_injection_payloads() -> List[str]:
return [
"' OR '1'='1",
"' OR '1'='1' --",
"1; DROP TABLE users--",
"admin'--",
]
@staticmethod
def number_mutations() -> []:
[
, -, ,
-,
(), (),
]
() -> :
chars = string.ascii_letters + string.digits + string.punctuation
.join(random.choice(chars) _ (length))
:
():
input_value FuzzInputGenerator.string_mutations():
response = requests.post(
,
json={: input_value, : },
timeout=
)
response.status_code < , \
response.status_code >= :
response.json()
():
payload FuzzInputGenerator.sql_injection_payloads():
response = requests.post(
,
json={: payload, : payload},
timeout=
)
response.status_code != , \
response.status_code >= :
error_text = response.text.lower()
error_text
error_text
():
value FuzzInputGenerator.number_mutations():
response = requests.post(
,
json={
: ,
: ,
: value
},
timeout=
)
response.status_code <
():
_ ():
random_data = {
: FuzzInputGenerator.generate_random_string(random.randint(, )),
: FuzzInputGenerator.generate_random_string(),
: random.randint(-, ),
}
response = requests.post(
,
json=random_data,
timeout=
)
response.status_code <
():
malicious_headers = {
: ,
: ,
: ,
}
response = requests.get(
,
headers=malicious_headers,
timeout=
)
response.status_code <
Example Usage
Example 1: Automated Fuzzing in CI/CD
name: API Fuzz Testing
on: [push, pull_request]
jobs:
fuzz:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Start API server
run: npm run start:test &
- name: Wait for API
run: npx wait-on http:
- name: Run fuzz tests
run: npm run test:fuzz
- name: Upload fuzz report
if: failure()
uses: actions/upload-artifact@v2
with:
name: fuzz-report
path: ./fuzz-report.html
Example 2: Custom Fuzzer with OpenAPI Spec
const SwaggerParser = require('@apidevtools/swagger-parser');
const axios = require('axios');
async function fuzzFromOpenAPI(specPath) {
const api = await SwaggerParser.validate(specPath);
for (const [path, methods] of Object.entries(api.paths)) {
for (const [method, operation] of Object.entries(methods)) {
if (method === 'get' || method === 'post') {
console.log(`Fuzzing ${method.toUpperCase()} ${path}`);
const fuzzInputs = generateFuzzInputs(operation.parameters);
for (const input of fuzzInputs) {
const response = await axios[method](
`${api.servers[0].url}${path}`,
input,
{ validateStatus: }
);
(response. === ) {
.(, input);
}
}
}
}
}
}
() {
[
];
}
();
Example 3: Continuous Fuzzing with AFL-inspired Approach
import requests
import random
import json
from datetime import datetime
class ContinuousFuzzer:
"""Continuously fuzz API endpoints with mutations"""
def __init__(self, base_url: str, endpoints: list):
self.base_url = base_url
self.endpoints = endpoints
self.crashes = []
def mutate_string(self, s: str) -> str:
"""Mutate string with random changes"""
mutations = [
lambda x: x + chr(random.randint(0, 255)),
lambda x: x[:len(x)//2],
lambda x: x * 100,
lambda x: x.replace('a', '<script>'),
lambda x: x + "' OR '1'='1",
]
return random.choice(mutations)(s)
def fuzz_endpoint(self, endpoint: str, method: str = ):
seed_data = {: , : }
_ ():
fuzzed_data = {}
key, value seed_data.items():
(value, ):
fuzzed_data[key] = .mutate_string(value)
:
fuzzed_data[key] = value
:
response = requests.request(
method,
,
json=fuzzed_data,
timeout=
)
response.status_code == :
.crashes.append({
: endpoint,
: fuzzed_data,
: response.text,
: datetime.now().isoformat()
})
requests.exceptions.Timeout:
.crashes.append({
: endpoint,
: fuzzed_data,
: ,
: datetime.now().isoformat()
})
():
time
start_time = time.time()
(time.time() - start_time) < (duration_minutes * ):
endpoint = random.choice(.endpoints)
.fuzz_endpoint(endpoint)
(, ) f:
json.dump(.crashes, f, indent=)
()
fuzzer = ContinuousFuzzer(
base_url=,
endpoints=[, , ]
)
fuzzer.run(duration_minutes=)
Error Handling
Common issues and solutions:
Problem: Fuzzer overwhelms API with requests
- Cause: No rate limiting in fuzzer
- Solution: Add delays between requests, respect API rate limits
Problem: False positives (valid errors reported as crashes)
- Cause: Fuzzer doesn't understand expected behavior
- Solution: Define expected error codes (400, 404), only flag 500s as crashes
Problem: Fuzzer credentials get rate-limited or blocked
- Cause: Too many failed auth attempts
- Solution: Use test credentials, whitelist test IPs, reset between runs
Problem: Fuzzing breaks production data
- Cause: Fuzzer running against production environment
- Solution: Always fuzz staging/test environments, use test data
Problem: Can't reproduce crashes
- Cause: Fuzzer doesn't log exact inputs that caused crashes
- Solution: Log all inputs, responses, timestamps for crash reproduction
Configuration
Fuzzer Configuration File
module.exports = {
target: {
baseUrl: process.env.API_URL || 'http://localhost:3000',
endpoints: [
{ path: '/api/users', method: 'POST' },
{ path: '/api/users/:id', method: 'GET' },
{ path: '/api/orders', method: 'POST' },
],
},
authentication: {
type: 'bearer',
token: process.env.TEST_API_TOKEN,
},
fuzzing: {
iterations: 1000,
timeout: 5000,
delay: 100,
concurrent: 5,
},
inputs: {
strings: true,
numbers: true,
sqlInjection: true,
: ,
: [
,
,
],
},
: {
: ,
: ,
: {
.(, crash);
},
},
: [
,
,
],
};
Best Practices
DO:
- Run fuzzing in staging/test environments, never production
- Log all crash-inducing inputs for reproducibility
- Integrate fuzzing into CI/CD pipeline
- Fuzz high-risk endpoints (auth, payment, admin) more thoroughly
- Use realistic seed data (from production, anonymized)
- Monitor API during fuzzing for crashes and anomalies
- Combine fuzzing with other security testing (SAST, DAST, pen testing)
DON'T:
- Fuzz production APIs without explicit permission
- Use production credentials or test accounts in fuzzer
- Ignore 400-level errors (they might indicate security issues)
- Run unbounded fuzzing (set time/iteration limits)
- Skip regression tests after fixing fuzz-discovered bugs
- Overlook API dependencies (databases, external APIs)
TIPS:
- Start with known payloads (OWASP, SecLists) before random fuzzing
- Use OpenAPI specs to auto-generate fuzz tests
- Combine grammar-based and mutation-based fuzzing
- Monitor server logs, not just HTTP responses
- Fuzz at multiple levels (headers, body, query params, path params)
- Use corpus of real user inputs as seed data
Related Commands
/scan-api-security - Comprehensive security scanning
/validate-schemas - Schema validation testing
/run-load-test - Performance testing under load
/generate-rest-api - Generate APIs with built-in validation
/implement-error-handling - Proper error handling to prevent info leaks
Performance Considerations
- Fuzzing throughput: 100-1000 requests/sec depending on API complexity
- Coverage: Aim for 80%+ code coverage with fuzz tests
- Duration: Run continuous fuzzing (1+ hours) to find rare bugs
- Resource usage: Monitor CPU/memory during fuzzing to detect leaks
Optimization strategies:
- Use parallel fuzzing with multiple workers
- Cache API responses to avoid redundant tests
- Prioritize high-risk endpoints for deeper fuzzing
- Use smart fuzzing (AFL-style coverage guidance)
Security Considerations
- Authorization: Fuzz with different permission levels (guest, user, admin)
- Rate limiting: Verify fuzzing doesn't bypass rate limits
- Logging: Ensure malicious inputs are logged for security monitoring
- Secrets: Never log sensitive data (passwords, tokens) from fuzz inputs
- Compliance: Document fuzzing for security compliance (SOC 2, ISO 27001)
Security checklist:
Troubleshooting
Fuzzer hangs or times out:
- Increase request timeout setting
- Check for infinite loops in API code
- Monitor API server resources (CPU, memory)
- Reduce concurrent fuzzing requests
No crashes found:
- Verify API is actually receiving fuzz inputs
- Check if input validation is too strict (rejecting all fuzz inputs)
- Increase fuzzing iterations
- Use smarter fuzzing strategies (grammar-based, mutation-based)
Too many false positives:
- Define expected error codes (400, 404, 401, 403)
- Only flag 500-level errors as crashes
- Review API logs to understand error causes
- Adjust fuzzer configuration
Can't reproduce crashes:
- Ensure fuzzer logs exact inputs that caused crashes
- Check if crash is timing-dependent (race condition)
- Verify environment matches (same data, same config)
- Use deterministic fuzzing (fixed seed) for reproducibility
Version History
- 1.0.0 (2025-10-11): Initial release with comprehensive fuzzing
- String, number, SQL, XSS payload generation
- Jest and pytest test suites
- OpenAPI-driven fuzzing
- Continuous fuzzing with crash detection
- CI/CD integration examples
- Security best practices and checklist