<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: implementing-api-security-gateway
description: >-
  Design and implement API security gateway configurations including rate limiting,
  authentication enforcement, request validation, CORS policies, and WAF rules
  for Kong, AWS API Gateway, and nginx-based API proxies.
domain: cybersecurity
subdomain: api-security
tags:
  - api-gateway
  - rate-limiting
  - waf
  - cors
  - api-security
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1190"]
  owasp-api: ["API4", "API5", "API8"]
  tools: ["kong", "nginx", "aws-api-gateway", "owasp-zap"]
---

# Implementing API Security Gateway

## Overview

An API security gateway enforces authentication, rate limiting, input validation,
and access control at the perimeter before requests reach backend services.
This skill covers hardened configuration for Kong, nginx, and AWS API Gateway.

## Prerequisites

- Tools: ["kong", "nginx", "aws-api-gateway", "owasp-zap"]
- Administrative access to API gateway
- Authorized configuration change window

## Key Concepts

- **Authentication enforcement**: Every endpoint requires valid credentials
- **Rate limiting**: Per-client request caps with progressive backoff
- **Input validation**: Schema-based request validation before routing
- **CORS policy**: Restrict origins, methods, and headers
- **Response filtering**: Strip sensitive fields from outbound responses

## Workflow

### Step 1: Kong Gateway Hardening

```bash
# Enable rate limiting plugin
curl -s -X POST http://kong:8001/services/api/plugins \
  -d "name=rate-limiting" \
  -d "config.minute=60" \
  -d "config.hour=1000" \
  -d "config.policy=local" \
  -d "config.limit_by=consumer"

# Enable JWT authentication
curl -s -X POST http://kong:8001/services/api/plugins \
  -d "name=jwt"

# Enable request size limiting
curl -s -X POST http://kong:8001/services/api/plugins \
  -d "name=request-size-limiting" \
  -d "config.allowed_payload_size=1"

# Enable CORS with strict policy
curl -s -X POST http://kong:8001/services/api/plugins \
  -d "name=cors" \
  -d "config.origins=https://app.target.com" \
  -d "config.methods=GET,POST,PUT,DELETE" \
  -d "config.headers=Authorization,Content-Type" \
  -d "config.max_age=3600"

# Enable request validation (OpenAPI spec)
curl -s -X POST http://kong:8001/services/api/plugins \
  -d "name=request-validator" \
  -d "config.body_schema=$(cat openapi-schema.json)"
```

### Step 2: Nginx API Gateway Configuration

```nginx
# /etc/nginx/conf.d/api-gateway.conf

# Rate limiting zones
limit_req_zone $binary_remote_addr zone=api_general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=api_auth:10m rate=3r/s;

# Connection limiting
limit_conn_zone $binary_remote_addr zone=api_conn:10m;

server {
    listen 443 ssl http2;
    server_name api.target.com;

    # TLS configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;

    # Security headers
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options DENY always;
    add_header Strict-Transport-Security "max-age=31536000" always;

    # Request size limit
    client_max_body_size 1m;
    client_body_buffer_size 16k;

    # Hide server version
    server_tokens off;

    # Authentication endpoint — strict rate limiting
    location /api/auth/ {
        limit_req zone=api_auth burst=5 nodelay;
        limit_conn api_conn 5;
        proxy_pass http://backend;
    }

    # General API — moderate rate limiting
    location /api/ {
        limit_req zone=api_general burst=20 nodelay;
        limit_conn api_conn 10;

        # CORS policy
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' 'https://app.target.com';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE';
            add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
            add_header 'Access-Control-Max-Age' 3600;
            return 204;
        }
        add_header 'Access-Control-Allow-Origin' 'https://app.target.com' always;

        proxy_pass http://backend;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_hide_header X-Powered-By;
    }

    # Block debug/internal endpoints
    location ~ ^/api/(debug|internal|admin) {
        deny all;
        return 403;
    }
}
```

### Step 3: AWS API Gateway Configuration

```bash
# Create usage plan with throttling
aws apigateway create-usage-plan \
  --name "standard" \
  --throttle burstLimit=50,rateLimit=100 \
  --quota limit=10000,period=DAY

# Enable request validation
aws apigateway create-request-validator \
  --rest-api-id API_ID \
  --name "full-validation" \
  --validate-request-body \
  --validate-request-parameters

# Set WAF ACL on API Gateway
aws wafv2 create-web-acl \
  --name "api-protection" \
  --scope REGIONAL \
  --default-action '{"Allow":{}}' \
  --rules file://waf-rules.json
```

### Step 4: Verification Testing

```bash
# Test rate limiting
for i in $(seq 1 100); do
  curl -s -o /dev/null -w "Request $i: %{http_code}\n" \
    https://api.target.com/api/test
done

# Test CORS enforcement
curl -si -H "Origin: https://evil.com" https://api.target.com/api/data | \
  grep -i "access-control"

# Test request size limits
dd if=/dev/urandom bs=2M count=1 2>/dev/null | \
  curl -s -o /dev/null -w "%{http_code}" -X POST \
    -H "Content-Type: application/octet-stream" \
    --data-binary @- https://api.target.com/api/upload

# OWASP ZAP API scan
zap-cli quick-scan -s all https://api.target.com/api
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| Rate limit hits | Gateway logs | Clients hitting rate ceilings |
| Request validation failures | Gateway logs | Malformed or oversized requests |
| CORS violations | WAF | Requests from non-whitelisted origins |
| Authentication failures | Auth logs | Invalid or missing tokens |

```yaml
title: API Gateway Rate Limit Exceeded
id: d0e1f2a3-b4c5-6789-d012-012345678901
status: experimental
description: Detects clients exceeding API rate limits indicating potential abuse
logsource:
  category: webserver
detection:
  selection:
    sc-status: 429
  timeframe: 5m
  condition: selection | count() by c-ip > 20
falsepositives:
  - Legitimate high-traffic API consumers during peak usage
level: medium
tags:
  - attack.t1190
  - attack.initial_access
```

## Verification

- [ ] Rate limiting enforced on all endpoints
- [ ] Authentication required on all non-public endpoints
- [ ] CORS policy restricts to known origins
- [ ] Request size limits configured
- [ ] Server version headers suppressed
- [ ] Debug/internal endpoints blocked

## References

- [Kong Gateway Plugins](https://docs.konghq.com/hub/)
- [OWASP API8:2023 — Security Misconfiguration](https://owasp.org/API-Security/editions/2023/en/0xa8-security-misconfiguration/)
- [nginx Rate Limiting](https://www.nginx.com/blog/rate-limiting-nginx/)
