---
name: api-gateway-security
description: Secure API gateways with authentication, authorization, rate limiting, request validation, WAF rules, CORS policies, TLS/SSL management, API security monitoring, bot detection, and abuse prevention. Use when configuring API gateway security, implementing authentication and authorization, setting up rate limiting, deploying WAF rules, managing API keys, configuring CORS, monitoring API security threats, or preventing API abuse. Triggers on phrases like "API gateway security", "rate limiting", "API authentication", "WAF rules", "CORS policy", "API key management", "request validation", "API abuse prevention", "API security monitoring", "bot detection", "API throttling", "OAuth", "JWT validation", "API security posture", "DDoS protection API".
---

# API Gateway Security

Protect APIs from abuse, unauthorized access, and common attack vectors at the gateway layer.

## Workflow

1. Define security requirements per API: authentication method, rate limits, access scopes, compliance classification.
2. Configure authentication: API keys, OAuth 2.0, JWT, mTLS, or hybrid approaches based on consumer type.
3. Set up authorization: role-based, scope-based, attribute-based, or policy-based access control.
4. Implement rate limiting: per-client, per-endpoint, per-API tier, with adaptive thresholds.
5. Deploy WAF rules: OWASP Top 10 protections, custom business logic attack rules, bot detection.
6. Configure TLS/SSL: certificate management, minimum TLS version, cipher suites, HSTS.
7. Set up CORS policies: allowed origins, methods, headers, preflight handling, wildcard restrictions.
8. Enable request/response validation: schema validation, payload size limits, header checks, parameter sanitization.
9. Monitor and alert: unusual traffic patterns, authentication failures, rate limit breaches, WAF blocks, bot activity.

## Authentication Architecture

### Multi-Tier Authentication Strategy

```
API AUTHENTICATION ARCHITECTURE
=================================

Authentication Methods by Consumer Type:
  ┌────────────────────────┬───────────────────┬──────────────────────────┬────────────────────────────┐
  │ Consumer Type          │ Methods           │ APIs Using This          │ Security Level             │
  ├────────────────────────┼───────────────────┼──────────────────────────┼────────────────────────────┤
  │ Internal services      │ mTLS + service    │ 42 APIs (100% internal)  │ HIGHEST — mutual auth +    │
  │ (service-to-service)   │ account token     │                          │ cert validation            │
  ├────────────────────────┼───────────────────┼──────────────────────────┼────────────────────────────┤
  │ Partner integrations   │ OAuth 2.0         │ 18 APIs (partner portal) │ HIGH — delegated auth +    │
  │ (B2B partners)         │ client credentials│                          │ scope-based access         │
  │                        │ + API key         │                          │                            │
  ├────────────────────────┼───────────────────┼──────────────────────────┼────────────────────────────┤
  │ Mobile/web apps        │ OAuth 2.0 + JWT   │ 24 APIs (consumer-facing)│ MEDIUM-HIGH — user auth +  │
  │ (end consumers)        │ (authorization   │                          │ short-lived tokens         │
  │                        │ code flow)        │                          │                            │
  ├────────────────────────┼───────────────────┼──────────────────────────┼────────────────────────────┤
  │ Public APIs            │ API key + rate    │ 8 APIs (public data)     │ MEDIUM — key-based +       │
  │                        │ limiting          │                          │ strict rate limits         │
  ├────────────────────────┼───────────────────┼──────────────────────────┼────────────────────────────┤
  │ Webhook receivers      │ HMAC signature    │ 6 APIs (webhook endpoints)│ HIGH — payload integrity   │
  │                        │ validation        │                          │ + source IP validation     │
  └────────────────────────┴───────────────────┴──────────────────────────┴────────────────────────────┘

JWT CONFIGURATION (OAuth 2.0 Flows):
  Issuer: https://auth.company.com
  JWK URI: https://auth.company.com/.well-known/jwks.json
  Algorithms: RS256 (asymmetric, mandatory) — HS256 disabled for production
  
  Token Lifecycle:
    Access token: 15 minutes (short-lived, per-request)
    Refresh token: 7 days (rotated on each use, stored server-side)
    ID token: 15 minutes (contains user profile claims)
    API key: 90 days (auto-expiry, notification at 14 days remaining)
  
  Required Claims:
    sub (subject): User or service account identifier — mandatory
    iss (issuer): "https://auth.company.com" — validated
    exp (expiration): Unix timestamp — validated, rejected if expired
    iat (issued at): Unix timestamp — validated, rejected if > 5 min skew
    aud (audience): API identifier — validated per endpoint
    scope: Granted permissions — validated against endpoint requirements
    roles: User roles — validated for RBAC enforcement
    jti: Unique token ID — validated against replay cache (5-minute window)
  
  JWT Validation Rules (Gateway Level):
    1. Signature verification: Against current JWK set (cached, 1-hour refresh)
    2. Expiration check: Rejected if exp < current time (with 60-second clock skew tolerance)
    3. Issuer validation: Must match "https://auth.company.com" (exact match)
    4. Audience validation: Must include the API identifier for this endpoint
    5. Not-before check: Rejected if nbf > current time (with 60-second tolerance)
    6. Token reuse detection: jti checked against sliding window cache (prevents replay)
    7. Claim presence check: All required claims must be present
    8. Scope validation: Token scope must include required scope for endpoint

API KEY MANAGEMENT:
  Total active API keys: 156
    Internal service keys: 42 (mTLS-backed, auto-rotated)
    Partner keys: 38 (manually rotated, 90-day expiry)
    Consumer app keys: 64 (auto-managed via OAuth)
    Public API keys: 12 (rate-limited, lower access level)
  
  Key Rotation Policy:
    Automatic: Internal keys (rotated every 30 days via cert-manager + Vault)
    Manual: Partner keys (notification at 30, 14, 7 days before expiry)
    Emergency: Compromised key revocation (immediate, propagates within 60 seconds)
  
  Key Scoping:
    Per-key access control: Specific APIs, specific endpoints, HTTP methods
    Rate limit per key: Independent of user limits (prevents key sharing abuse)
    Geographic scoping: Key valid only in specific regions (for compliance)
    Usage tracking: Per-key request count, error rate, latency (billing + abuse detection)
  
  Key Security:
    Storage: Hashed in database (SHA-256 with salt, never stored in plaintext)
    Transmission: HTTPS only (TLS 1.3, HSTS enforced)
    Logging: Key prefix logged (first 8 chars), full key never logged
    Revocation: Central revocation list (propagates to all gateway nodes in < 60 seconds)

OAUTH 2.0 IMPLEMENTATION:
  Supported Flows:
    Authorization Code + PKCE: Mobile and web apps (confidential + public clients)
    Client Credentials: Service-to-service (no user context)
    Device Authorization: Limited-input devices (TVs, smart displays)
    NOT supported: Implicit flow (deprecated, insecure), Password grant (insecure)
  
  OAuth Server: Auth0 (managed) / Keycloak (self-hosted fallback)
  Client Registry: 89 registered clients (42 internal, 24 partner, 23 public)
  
  Token Endpoint Security:
    TLS: Required (mutual TLS for partner clients)
    Rate limiting: 10 requests/minute per client (prevents brute force)
    Replay protection: nonce validation (required for all token requests)
    Binding: token_binding extension for DPoP (Demonstrating Proof of Possession)
  
  Refresh Token Rotation:
    Each refresh token use generates new refresh token (old one invalidated)
    Token chaining detection: Alert if refresh chain > 20 tokens (potential theft)
    Absolute expiry: 30 days (even with continuous refresh, forces re-authentication)
    Session binding: Refresh token tied to session ID (invalidated on session end)
```

### Authorization Framework

```
API AUTHORIZATION FRAMEWORK
=============================

Authorization Model: ABAC (Attribute-Based Access Control) + RBAC hybrid

ATTRIBUTE DIMENSIONS:
  Subject attributes: user_id, roles, department, clearance_level, mfa_enabled
  Resource attributes: api_id, endpoint, data_classification, owner_team
  Action attributes: http_method, scope, permission_level
  Environment attributes: time_of_day, ip_address, geo_location, device_trust_score
  Policy attributes: compliance_requirements, regulatory_constraints

AUTHORIZATION DECISION ENGINE:
  Engine: Open Policy Agent (OPA) with Rego policies
  Policy evaluation time: < 2ms (cached policies, compiled Rego)
  Policy cache: Redis (300-second TTL, invalidated on policy change)
  Fallback: Deny-all (if policy engine unavailable)

POLICY CATEGORIES:
  ┌──────────────────────────┬────────────────────────┬────────────────────────────┐
  │ Policy Type              │ Rules                  │ Enforcement                │
  ├──────────────────────────┼────────────────────────┼────────────────────────────┤
  │ Role-based (RBAC)        │ 48 policies            │ Hard block                 │
  │ Scope-based              │ 36 policies            │ Hard block                 │
  │ Attribute-based (ABAC)   │ 24 policies            │ Hard block                 │
  │ Time-based               │ 8 policies             │ Hard block                 │
  │ Geo-based                │ 6 policies             │ Hard block (compliance)    │
  │ Rate-limit-based         │ 12 policies            │ Soft throttle → hard block │
  │ Conditional              │ 16 policies            │ Dynamic (risk-score based) │
  │ Custom business logic    │ 22 policies            │ Hard block                 │
  └──────────────────────────┴────────────────────────┴────────────────────────────┘

SAMPLE POLICIES:

  1. ROLE-BASED: Admin API Access
     ALLOW if:
       user.roles contains "admin"
       AND user.mfa_enabled == true
       AND resource.api_id in admin_apis
     DENY otherwise
     Audit: All decisions logged (allow + deny)

  2. SCOPE-BASED: Payment Data Access
     ALLOW if:
       token.scope contains "payments:read" (for GET)
       OR token.scope contains "payments:write" (for POST/PUT/DELETE)
       AND resource.api_id == "payment-service"
     DENY otherwise
     Audit: All payment API access logged (PCI DSS requirement)

  3. ATTRIBUTE-BASED: Data Classification Access
     ALLOW if:
       user.clearance_level >= resource.data_classification
       AND user.department == resource.owner_team (for classified data)
     DENY otherwise
     Levels: public (0) < internal (1) < confidential (2) < restricted (3)

  4. TIME-BASED: After-Hours Restriction
     ALLOW if:
       current_time between 06:00 and 22:00 (company timezone)
       OR user.roles contains "oncall-admin" (emergency access)
     DENY otherwise
     Applies to: Sensitive APIs (payment processing, user data modification)

  5. GEO-BASED: EU Data Access (GDPR)
     ALLOW if:
       request.geo_location in EU_countries
       AND resource.api_id in eu_apis
       AND user.consent_granted == true
     DENY otherwise
     Compliance: GDPR Article 44 (transfers to third countries)

  6. RISK-SCORE BASED: Adaptive Authentication
     ALLOW if:
       request.risk_score < 30 (low risk — standard access)
     CHALLENGE if:
       request.risk_score between 30 and 70 (medium risk — step-up MFA required)
     DENY if:
       request.risk_score > 70 (high risk — block + alert)
     Risk factors: IP reputation, device fingerprint, behavioral anomaly, geo velocity

ACCESS REVIEW & CERTIFICATION:
  Quarterly access review: All API access certified by data owners
    - Access report generated (user × API × role matrix)
    - Manager certification: "Confirm this user needs this access"
    - Auto-remediation: Uncertified access revoked after 14-day grace period
    - Compliance: SOX, SOC 2, PCI DSS requirement
    
  Last review (Q1 2025):
    Total access entries reviewed: 4,820
    Certified (confirmed): 4,612 (95.7%)
    Revoked (no longer needed): 178 (3.7%)
    Escalated (disputed): 30 (0.6%) — resolved by data owner
    Uncertified (auto-revoked): 0 (all completed within grace period)
```

## Rate Limiting Strategy

### Enterprise Rate Limiting Architecture

```
RATE LIMITING — ENTERPRISE ARCHITECTURE
=========================================

Rate Limiting Engine: Kong Rate-Limiting Plugin + Custom Redis-backed Limiter
Storage: Redis Cluster (6 nodes, distributed, high availability)
Algorithm: Token bucket (smooth burst handling) + Sliding window (distributed accuracy)

TIERED RATE LIMITS:
  ┌──────────────────┬──────────────┬──────────────┬──────────────┬──────────────┬────────────────────┐
  │ Tier             │ Req/minute   │ Req/hour     │ Req/day      │ Concurrent   │ APIs Covered       │
  ├──────────────────┼──────────────┼──────────────┼──────────────┼──────────────┼────────────────────┤
  │ Free             │ 30           │ 500          │ 5,000        │ 5            │ Public data APIs   │
  │ Basic ($49/mo)   │ 100          │ 3,000        │ 25,000       │ 15           │ Standard APIs      │
  │ Pro ($199/mo)    │ 500          │ 15,000       │ 100,000      │ 50           │ All APIs           │
  │ Enterprise       │ 2,000        │ 60,000       │ 500,000      │ 200          │ All APIs + priority│
  │ Internal         │ 10,000       │ Unlimited    │ Unlimited    │ 500          │ Internal services  │
  │ Partner          │ Custom       │ Custom       │ Custom       │ Custom       │ Per-contract SLA   │
  └──────────────────┴──────────────┴──────────────┴──────────────┴──────────────┴────────────────────┘

PER-ENDPOINT RATE LIMITS (stricter for resource-intensive operations):
  /api/v1/search: 20 req/min (full-text search, resource-intensive)
  /api/v1/upload: 5 req/min (bandwidth-heavy, large payloads)
  /api/v1/auth/login: 10 req/min (brute-force prevention)
  /api/v1/auth/reset-password: 3 req/min (account lockout prevention)
  /api/v1/export: 2 req/min (heavy computation, large response)
  /api/v1/webhook: 100 req/min (notification handler, higher tolerance)
  /api/v1/recommendations: 30 req/min (ML inference, moderate cost)
  Default: Inherits tier limit (if no endpoint-specific limit)

BURST HANDLING:
  Allowed burst: 2x normal rate for up to 10 seconds (token bucket refill rate)
  Burst cooldown: Rate returns to normal after burst period
  Burst tracking: Per-client burst history (abuse detection)
  Burst abuse: Clients exceeding burst > 3 times/hour flagged for review

RATE LIMIT RESPONSE:
  HTTP Status: 429 Too Many Requests
  Response body:
    {
      "error": "rate_limit_exceeded",
      "message": "You have exceeded your rate limit. Please retry after 30 seconds.",
      "retry_after": 30,
      "current_limit": 100,
      "remaining": 0,
      "reset_at": "2025-01-20T14:30:00Z",
      "tier": "Basic",
      "upgrade_url": "https://company.com/pricing"
    }
  Response headers:
    X-RateLimit-Limit: 100
    X-RateLimit-Remaining: 0
    X-RateLimit-Reset: 1705759800
    Retry-After: 30
    Retry-After-Date: Sat, 20 Jan 2025 14:30:00 GMT

RATE LIMIT MONITORING (Last 30 Days):
  Total rate-limited requests: 24,680 (0.05% of total traffic)
  By tier:
    Free tier: 18,420 (74.6%) — expected (lowest limits, highest volume)
    Basic tier: 4,280 (17.3%) — normal
    Pro tier: 1,420 (5.7%) — within tolerance
    Enterprise: 380 (1.5%) — monitoring for potential issue
    Internal: 180 (0.7%) — investigating (should be minimal)
  
  Top rate-limited clients:
    1. Unknown bot (IP: 45.x.x.x): 4,200 requests blocked — added to blocklist
    2. Scraper service (API key: sk_abc...): 2,800 requests blocked — notified owner, key suspended
    3. Misconfigured app (API key: pk_xyz...): 1,600 requests blocked — developer contacted, config fixed
    4. Load testing (internal): 800 requests — expected (QA team, scheduled)
    5. Partner integration (API key: pt_def...): 420 requests — rate limit increased per SLA

ADAPTIVE RATE LIMITING (ML-based):
  Model: Real-time anomaly detection (isolation forest)
  Features: request rate, error rate, response time, geo distribution, user agent
  Detection: Clients deviating from normal pattern (z-score > 3)
  Action: Temporary rate limit reduction (50% of normal) + alert
  Recovery: Automatic restoration after 30 minutes (if behavior normalizes)
  
  Recent adaptive actions:
    1. IP 104.x.x.x: Spike to 500 req/min (normal: 30) — throttled, then restored (transient)
    2. API key ak_ghi...: Gradual increase (20 → 200 req/min over 2 hours) — throttled, owner notified
    3. Geo anomaly: 80 requests from country with 0 historical traffic — flagged for review
```

## WAF Rules & Protection

### Web Application Firewall Configuration

```
WAF — ACTIVE RULE SETS
========================

WAF Platform: AWS WAF (managed) + ModSecurity (custom rules, legacy APIs)
Total Active Rules: 134 (across all categories)
Rule Evaluation: Per-request (cached compiled rules, < 1ms overhead per rule set)

RULE CATEGORIES:
  ┌───────────────────────────┬────────────┬──────────────────────┬──────────────────────┐
  │ Category                  │ Rules      │ Monthly Blocks       │ False Positive Rate  │
  ├───────────────────────────┼────────────┼──────────────────────┼──────────────────────┤
  │ OWASP Top 10 (2021)      │ 48         │ 2,340 avg            │ 0.002%               │
  │ SQL Injection            │ 12         │ 180 avg              │ 0.001%               │
  │ Cross-Site Scripting     │ 15         │ 420 avg              │ 0.003%               │
  │ Bot Detection            │ 8          │ 1,200 avg            │ 0.005%               │
  │ Rate Attack Protection   │ 6          │ 380 avg              │ 0.001%               │
  │ Custom Business Rules    │ 22         │ 156 avg              │ 0.004%               │
  │ Geo-blocking             │ 3          │ 89 avg               │ 0.001%               │
  │ File Upload Protection   │ 5          │ 34 avg               │ 0.002%               │
  │ Data Exfiltration        │ 7          │ 12 avg               │ 0.001%               │
  │ API-specific rules       │ 8          │ 240 avg              │ 0.003%               │
  │ DDoS mitigation          │ 10         │ 890 avg              │ 0.002%               │
  │ Credential stuffing      │ 4          │ 156 avg              │ 0.001%               │
  │ Scraping prevention      │ 6          │ 320 avg              │ 0.004%               │
  └───────────────────────────┴────────────┴──────────────────────┴──────────────────────┘
  Total monthly blocks: 6,417 (0.013% of 48.2M monthly requests)
  Total false positives: 96/month (0.002% of blocked requests)

OWASP TOP 10 RULES (Key Protections):
  A01: Broken Access Control
    - Path traversal detection (../, %2e%2e, etc.)
    - IDOR prevention (sequential ID enumeration detection)
    - Privilege escalation detection (unauthorized admin endpoint access)
  
  A02: Cryptographic Failures
    - Enforce HTTPS (redirect HTTP to HTTPS, HSTS header)
    - Block requests with credentials in URL
    - Validate TLS version (reject TLS 1.0, 1.1)
  
  A03: Injection
    - SQL injection patterns (UNION, OR 1=1, DROP TABLE, etc.)
    - NoSQL injection patterns ({$gt: }, {$ne: null}, etc.)
    - Command injection patterns (;, |, &&, $(, `, etc.)
    - XSS patterns (<script>, javascript:, onerror=, etc.)
    - LDAP injection patterns (*, )(|, (&, etc.)
  
  A05: Security Misconfiguration
    - Block requests with suspicious headers (X-Forwarded-For spoofing)
    - Validate Host header (prevent host header injection)
    - Detect server information leakage (block verbose error responses)
  
  A07: Identification & Authentication Failures
    - Brute force detection (> 5 failed logins in 5 minutes → block IP for 30 minutes)
    - Credential stuffing detection (same IP, multiple usernames → block + alert)
    - Account enumeration prevention (generic error messages for invalid credentials)

CUSTOM BUSINESS RULES:
  1. API version header validation:
     BLOCK if: X-API-Version header missing OR not in allowlist (v1, v2, v3)
     Purpose: Prevent unversioned access, enforce API lifecycle

  2. Payload schema enforcement:
     BLOCK if: Request body doesn't match JSON Schema for endpoint
     Purpose: Prevent malformed requests, enforce API contract
     Coverage: 28 mutation endpoints (POST, PUT, DELETE)

  3. Webhook signature validation:
     BLOCK if: X-Webhook-Signature header missing OR HMAC-SHA256 verification fails
     Purpose: Prevent webhook injection, ensure payload integrity
     Secret: Per-webhook secret stored in Vault, rotated every 90 days

  4. Business rate limiting (beyond technical limits):
     BLOCK if: User creates > 10 accounts in 24 hours (prevents fake accounts)
     BLOCK if: User resets password > 3 times in 1 hour (prevents account lockout abuse)
     BLOCK if: Same IP submits > 50 support tickets in 1 hour (prevents spam)

  5. Geographic restrictions:
     BLOCK if: Request from sanctioned country (OFAC list, updated weekly)
     BLOCK if: EU data API accessed from non-EU region (GDPR compliance)
     ALLOWLIST: Specific IPs can be exempted (partner offices, data centers)

WAF MODES:
  BLOCK mode: Production (default) — actively blocks matching requests
  LOG mode: Staging + new rules — logs matches without blocking (48-hour testing period)
  BYPASS: Emergency — whitelist specific IP/rule (requires approval, auto-expiry 4 hours)
  
  Last 30 days:
    Rules in BLOCK mode: 126 (94%)
    Rules in LOG mode: 8 (6%) — new rules under evaluation
    Bypasses used: 3 (all emergency, all resolved within 2 hours)
    Bypass reasons:
      1. Legitimate traffic blocked (false positive) — rule updated
      2. Partner IP blocked (missing from allowlist) — IP added to allowlist
      3. Internal scanning tool blocked — tool IP whitelisted temporarily

BOT DETECTION:
  Bot types detected:
    Good bots: Googlebot, Bingbot, Slurp (allowlisted via User-Agent + IP range verification)
    Bad bots: Scrapers, credential stuffers, API abusers (blocked or rate-limited)
    Unknown bots: Challenged with JavaScript challenge or CAPTCHA
  
  Bot management: Akamai Bot Manager (managed) + Custom challenge page
  Monthly bot traffic: 1,200 blocked (2.5% of total traffic is bot attempts)
  CAPTCHA challenge success rate: 78% (humans pass, bots fail)
  Challenge false positive rate: 2.1% (legitimate users challenged — being optimized)
```

## TLS/SSL & CORS Configuration

```
TLS/SSL CONFIGURATION
======================

Certificate Management:
  Provider: cert-manager (Let's Encrypt) + DigiCert (enterprise, EV certs)
  Auto-renewal: 30 days before expiry (cert-manager automated)
  Minimum TLS version: TLS 1.2 enforced (TLS 1.3 preferred, negotiated automatically)
  HSTS: Enabled (max-age: 31536000 seconds = 1 year, includeSubDomains, preload)
  OCSP Stapling: Enabled (reduces TLS handshake latency by ~50ms)

Cipher Suites (TLS 1.3):
  TLS_AES_256_GCM_SHA384 (primary — strongest encryption)
  TLS_CHACHA20_POLY1305_SHA256 (secondary — mobile optimization)
  TLS_AES_128_GCM_SHA256 (fallback — broader compatibility)

TLS 1.2 Fallback Ciphers (for legacy clients):
  ECDHE-RSA-AES256-GCM-SHA384 (preferred)
  ECDHE-RSA-AES128-GCM-SHA256
  DHE-RSA-AES256-GCM-SHA384

Certificate Health Dashboard:
  Total certificates: 24 (across environments and subdomains)
    Production: 12 (8 TLS 1.3, 4 TLS 1.2 fallback)
    Staging: 6
    Development: 4
  Expiring within 30 days: 0 ✓
  Expiring within 60 days: 3 (auto-renewal scheduled)
  All certificates: Valid, trusted CAs, complete chain of trust
  EV certificates: 2 (payment portal, admin portal — for enhanced trust)

TLS PERFORMANCE:
  Average TLS handshake time: 45ms (TLS 1.3: 22ms, TLS 1.2: 68ms)
  Session resumption rate: 72% (TLS session tickets + OCSP stapling)
  TLS 1.3 adoption: 86% of connections (up from 62% last quarter)
  TLS 1.2 connections: 12% (legacy browsers, mobile apps)
  TLS 1.0/1.1 connections: 2% (blocked, returning 403)

CORS POLICY CONFIGURATION
===========================

CORS Engine: Kong CORS Plugin + Custom Middleware (complex policies)
Policy Model: Per-API whitelist (no global wildcard — security best practice)

GLOBAL CORS SETTINGS:
  Allowed methods: GET, POST, PUT, DELETE, PATCH, OPTIONS (preflight)
  Allowed headers: Content-Type, Authorization, X-API-Key, X-Request-ID, X-CSRF-Token
  Exposed headers: X-RateLimit-Remaining, X-RateLimit-Reset, X-Request-ID
  Max age (preflight cache): 3,600 seconds (1 hour)
  Credentials: Supported (with explicit origin — no wildcard with credentials)
  Vary: Origin header (enforced for proper caching)

PER-API CORS CONFIGURATION:
  /api/v1/consumer:
    Origins: ['https://app.company.com', 'https://www.company.com', 'https://*.company.com']
    Methods: GET, POST
    Credentials: true
    Max age: 3,600 seconds
  
  /api/v1/partner:
    Origins: ['https://partner1.com', 'https://partner2.com', 'https://portal.partner3.com']
    Methods: GET, POST, PUT
    Credentials: false
    Max age: 7,200 seconds
  
  /api/v1/internal:
    Origins: ['https://internal.company.com']
    Methods: GET, POST, PUT, DELETE
    Credentials: true
    Max age: 1,800 seconds
  
  /api/v1/public:
    Origins: ['*'] (wildcard — read-only, no credentials, no sensitive data)
    Methods: GET
    Credentials: false
    Max age: 8,6400 seconds (1 day)

CORS VIOLATION LOGGING:
  Blocked CORS requests: 234/month (0.0005% of traffic — negligible)
  Common violations:
    Wrong origin (65%): Client configured with wrong base URL — developer education
    Preflight missing (30%): Client not sending OPTIONS preflight — SDK update needed
    Invalid methods (5%): Client sending unsupported HTTP method — API documentation check
  
  CORS violation alerting:
    Threshold: > 100 violations/hour from single origin → alert to API team
    Action: Investigate if legitimate (update allowlist) or malicious (block origin)
```

## Integration Points

- API gateways: Kong, Apigee, AWS API Gateway, NGINX Plus, Traefik, MuleSoft, Azure API Management
- Authentication: Auth0, Okta, Keycloak, AWS Cognito, Ping Identity, Azure AD B2C
- Authorization: Open Policy Agent (OPA), CASB platforms, custom ABAC engine
- WAF: AWS WAF, Cloudflare WAF, Azure WAF, Akamai WAF, ModSecurity, F5 ASM
- Rate limiting: Redis (token bucket), Nginx limit_req, Kong rate-limiting plugin, custom service
- TLS management: cert-manager (Kubernetes), AWS ACM, HashiCorp Vault PKI, Venafi
- Bot management: Akamai Bot Manager, Cloudflare Bot Management, PerimeterX, Shape Security
- Monitoring: Datadog API Monitoring, New Relic, Splunk, Prometheus/Grafana, Honeycomb
- SIEM: Splunk Enterprise Security, Azure Sentinel, IBM QRadar, Sumo Logic
- Load balancers: AWS ALB, NGINX, HAProxy, F5 BIG-IP, Gloo Edge
- API security testing: OWASP ZAP, Burp Suite, Postman (security tests), 42Crunch

## Edge Cases

- **Legitimate high-volume client blocked by rate limiting**: Implement API tier negotiation; enterprise clients get custom limits via SLA. Use adaptive rate limiting (ML-based) to distinguish between abuse and legitimate burst.

- **OAuth token validation latency**: JWK cache miss causes 200ms+ delay per request. Mitigation: (1) cache JWK set with 1-hour TTL, (2) pre-fetch on rotation (monitor JWK change events), (3) local JWK fallback if auth server unavailable (with staleness check).

- **CORS policy conflicts in multi-tenant**: Tenant A allows origin X, Tenant B blocks origin X. Resolution: per-tenant CORS configuration, evaluated after tenant identification (subdomain or header-based routing).

- **WAF false positive blocking legitimate traffic**: New API endpoint uses patterns matching SQL injection rules. Mitigation: (1) deploy new rules in LOG mode for 48 hours, (2) analyze logs for false positives, (3) create allowlist rule for specific endpoint, (4) tune WAF rule specificity.

- **Certificate emergency expiry (automation failure)**: cert-manager fails to renew. Prevention: (1) monitoring with PagerDuty alert at 30, 14, 7, 3, 1 days before expiry, (2) automated renewal testing in staging, (3) manual renewal runbook with step-by-step instructions, (4) certificate backup in Vault.

- **mTLS certificate rotation disruption**: Client certificate expires during rotation window. Mitigation: (1) 30-day overlap period (both old and new certs valid), (2) automated CSR generation and signing, (3) client notification at 60, 30, 14 days, (4) automated cert deployment via configuration management (Ansible, Fleet).

- **Cross-region API gateway consistency**: WAF rules differ between regions due to deployment lag. Resolution: (1) centralized WAF rule management (single source of truth), (2) automated rule deployment to all regions (CI/CD pipeline), (3) drift detection (alert if rules differ between regions), (4) canary deployment (deploy to one region first, validate, then roll out).

- **DDoS attack targeting API**: Volumetric attack overwhelming gateway. Response: (1) automatic rate limiting increase (aggregate level), (2) WAF rule tightening (block suspicious patterns), (3) CDN caching for GET endpoints (absorb traffic), (4) DDoS mitigation service activation (AWS Shield, Cloudflare Magic), (5) IP reputation blocking (known bad actors).

- **API key compromise**: Key leaked in public repository. Response: (1) immediate revocation (propagates in < 60 seconds), (2) usage audit (identify unauthorized access), (3) affected data assessment (scope of exposure), (4) notification (customer if personal data accessed), (5) new key generation + distribution, (6) root cause analysis (how was key exposed), (7) preventive measures (secret scanning in CI/CD).

- **OAuth token replay attack**: Interceptor replays captured access token. Prevention: (1) short-lived tokens (15 minutes), (2) token binding (DPoP — Demonstrating Proof of Possession), (3) jti (JWT ID) replay cache (5-minute window), (4) IP/device binding (token only valid from issuing device), (5) anomalous usage detection (geo velocity, behavioral analysis).
