<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: detecting-api-schema-violations
description: >-
  Detect and prevent API schema violations by validating request and response
  payloads against OpenAPI/Swagger specifications to identify injection attempts,
  type confusion, and data exfiltration through unexpected fields.
domain: cybersecurity
subdomain: api-security
tags:
  - schema-validation
  - api-security
  - openapi
  - input-validation
  - type-confusion
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1190", "T1059"]
  owasp-api: ["API3", "API8"]
  tools: ["curl", "nuclei", "spectral", "openapi-diff"]
---

# Detecting API Schema Violations

## Overview

API schema violations occur when requests or responses deviate from the
defined contract. Attackers exploit weak validation to inject unexpected
types, oversized payloads, or malformed data. Schema enforcement is a
foundational defense layer — OWASP API8:2023 Security Misconfiguration
and API3:2023 both depend on strict schema validation.

## Prerequisites

- Tools: ["curl", "nuclei", "spectral", "openapi-diff"]
- OpenAPI/Swagger specification for the target API
- Access to API gateway or validation middleware configuration
- Authorized testing engagement with written scope

## Key Concepts

- **Schema-first design**: API contract defined before implementation
- **Request validation**: Reject payloads not matching defined schema
- **Response validation**: Detect data leakage through extra response fields
- **Type coercion attacks**: Sending strings where integers expected, arrays where objects expected

## Workflow

### Step 1: Validate the OpenAPI Specification

```bash
# Lint OpenAPI spec for security issues
spectral lint openapi.yaml --ruleset .spectral.yaml

# Check for missing security definitions
grep -c 'security:' openapi.yaml
grep -c 'securityDefinitions\|securitySchemes' openapi.yaml

# Identify endpoints without schema definitions
python3 -c "
import yaml, sys
with open('openapi.yaml') as f:
    spec = yaml.safe_load(f)
for path, methods in spec.get('paths', {}).items():
    for method, details in methods.items():
        if method in ('get','post','put','patch','delete'):
            rb = details.get('requestBody', {})
            if method in ('post','put','patch') and not rb:
                print(f'MISSING REQUEST SCHEMA: {method.upper()} {path}')
            resps = details.get('responses', {})
            for code, resp in resps.items():
                if not resp.get('content'):
                    print(f'MISSING RESPONSE SCHEMA: {method.upper()} {path} [{code}]')
"
```

### Step 2: Test Type Confusion Attacks

```bash
# Send wrong types to trigger type coercion
# String where integer expected
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"id":"abc","quantity":"not_a_number"}' \
  https://target.com/api/orders

# Array where object expected
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user": [1,2,3]}' \
  https://target.com/api/users

# Null injection
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"email":null,"name":null,"role":null}' \
  https://target.com/api/users

# Nested object depth attack
python3 -c "
import json
payload = {'a': None}
current = payload
for i in range(100):
    current['a'] = {'a': None}
    current = current['a']
print(json.dumps(payload))
" | curl -s -X POST -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d @- https://target.com/api/data
```

### Step 3: Test Boundary Violations

```bash
# Oversized string fields
python3 -c "print('{\"name\":\"' + 'A'*100000 + '\"}')" | \
  curl -s -X POST -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d @- https://target.com/api/users

# Negative numbers where positive expected
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"quantity":-1,"price":-100}' \
  https://target.com/api/orders

# Oversized array
python3 -c "import json; print(json.dumps({'items': list(range(100000))}))" | \
  curl -s -X POST -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d @- https://target.com/api/batch
```

### Step 4: Detect Response Schema Drift

```bash
# Compare actual response against schema
python3 -c "
import json, subprocess, yaml

with open('openapi.yaml') as f:
    spec = yaml.safe_load(f)

result = subprocess.run(
    ['curl', '-s', '-H', 'Authorization: Bearer TOKEN',
     'https://target.com/api/users/me'],
    capture_output=True, text=True
)
response = json.loads(result.stdout)
expected_fields = set(spec['components']['schemas']['User']['properties'].keys())
actual_fields = set(response.keys())
extra = actual_fields - expected_fields
if extra:
    print(f'EXTRA FIELDS IN RESPONSE (data exposure risk): {extra}')
missing = expected_fields - actual_fields
if missing:
    print(f'MISSING FIELDS: {missing}')
"
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| Schema validation failures | API gateway | Requests failing schema checks |
| Type mismatch errors | Application logs | Wrong type sent for fields |
| Oversized payloads | WAF | Request body exceeding expected size |
| Unknown fields in requests | Validation middleware | Fields not in schema |

```yaml
title: API Schema Violation — Type Confusion Attempt
id: d4e5f6a7-b8c9-0123-defa-234567890123
status: experimental
description: Detects API requests with unexpected data types indicating schema abuse
logsource:
  category: application
detection:
  selection:
    event_type: schema_validation_error
    error_type:
      - type_mismatch
      - unknown_property
      - invalid_format
  timeframe: 5m
  condition: selection | count() by source_ip > 10
falsepositives:
  - Mobile clients with outdated schema versions
level: medium
tags:
  - attack.t1190
  - attack.initial_access
```

## Verification

- [ ] OpenAPI spec linted for security gaps
- [ ] Type confusion attacks tested on all endpoints
- [ ] Boundary violations tested (oversized, negative, nested)
- [ ] Response schema drift checked for data leakage
- [ ] Schema validation middleware enforcing strict mode
- [ ] Unknown fields rejected (not silently ignored)

## References

- [OWASP API8:2023 — Security Misconfiguration](https://owasp.org/API-Security/editions/2023/en/0xa8-security-misconfiguration/)
- [Spectral OpenAPI Linter](https://stoplight.io/open-source/spectral)
- [JSON Schema Specification](https://json-schema.org/specification.html)
