<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: designing-secure-api-architecture
description: >-
  Design secure API architectures with authentication, authorization, rate limiting,
  input validation, schema enforcement, and API gateway patterns across REST, GraphQL,
  and gRPC services.
domain: cybersecurity
subdomain: security-architecture
tags:
  - api-security
  - oauth2
  - openapi
  - rate-limiting
  - api-gateway
  - input-validation
  - graphql-security
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1190"]
---

# Designing Secure API Architecture

## Overview

APIs are the primary attack surface for modern applications. This skill covers
designing API security architecture including authentication (OAuth 2.0, mTLS),
authorization (RBAC/ABAC), rate limiting, input validation, and API gateway
patterns that enforce security at the edge.

Mode: `[MODE: ARCHITECT]` — API security design.

## Prerequisites

| Requirement | Details |
|---|---|
| OpenAPI/Swagger specifications for target APIs | Required |
| API gateway (Kong, AWS API Gateway, Apigee, or equivalent) | Required |
| OAuth 2.0 / OIDC provider | Required |
| Python 3.10+ | Required |

## Key Concepts

### API Security Architecture

```
                     ┌─────────────────────────┐
    Client ─────────►│      API Gateway         │
    (mTLS/OAuth)     │  ┌─────────────────────┐ │
                     │  │ Rate Limiting        │ │
                     │  │ Authentication       │ │
                     │  │ Schema Validation    │ │
                     │  │ Request Logging      │ │
                     │  └─────────────────────┘ │
                     └───────────┬───────────────┘
                                 │
                     ┌───────────▼───────────────┐
                     │    Service Mesh (mTLS)     │
                     ├───────┬───────┬────────────┤
                     │ Svc A │ Svc B │ Svc C      │
                     └───────┴───────┴────────────┘
```

### OAuth 2.0 Token Validation

```python
import jwt
from functools import wraps

def require_auth(scopes: list[str] | None = None):
    """Decorator for OAuth 2.0 token validation."""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            token = extract_bearer_token(request.headers)
            if not token:
                return {"error": "missing_token"}, 401

            try:
                payload = jwt.decode(
                    token,
                    key=get_jwks_public_key(),
                    algorithms=["RS256"],
                    audience=API_AUDIENCE,
                    issuer=ISSUER_URL,
                )
            except jwt.ExpiredSignatureError:
                return {"error": "token_expired"}, 401
            except jwt.InvalidTokenError:
                return {"error": "invalid_token"}, 401

            if scopes:
                token_scopes = payload.get("scope", "").split()
                if not all(s in token_scopes for s in scopes):
                    return {"error": "insufficient_scope"}, 403

            return func(*args, **kwargs)
        return wrapper
    return decorator
```

### API Gateway Security Configuration (Kong)

```yaml
# Kong declarative config for API security
_format_version: "3.0"

services:
  - name: backend-api
    url: http://api-service:8080
    routes:
      - name: api-route
        paths: ["/api/v1"]
    plugins:
      - name: rate-limiting
        config:
          minute: 100
          hour: 1000
          policy: redis
          redis_host: redis
      - name: key-auth
        config:
          key_names: ["X-API-Key"]
      - name: request-size-limiting
        config:
          allowed_payload_size: 1  # MB
      - name: ip-restriction
        config:
          deny: ["192.168.0.0/16"]
      - name: bot-detection
        config:
          deny: ["hacker"]
      - name: cors
        config:
          origins: ["https://app.example.com"]
          methods: ["GET", "POST", "PUT", "DELETE"]
          headers: ["Authorization", "Content-Type"]
          max_age: 3600
```

### Input Validation with OpenAPI Schema

```bash
# Validate API requests against OpenAPI spec
pip install openapi-core

# Example: enforce strict schema validation
python3 -c "
from openapi_core import OpenAPI
api = OpenAPI.from_file_path('openapi.yaml')
# Validates request body, params, headers against schema
"
```

### GraphQL Security Controls

```python
# GraphQL query depth and complexity limiting
GRAPHQL_SECURITY = {
    "max_query_depth": 10,
    "max_query_complexity": 1000,
    "max_aliases": 5,
    "introspection_enabled": False,  # Disable in production
    "batch_limit": 5,
    "rate_limit_per_operation": {
        "query": 100,   # per minute
        "mutation": 20,  # per minute
    },
}
```

## Workflow

### Step 1: Audit Existing APIs

```bash
node scripts/agent.js --action audit --spec openapi.yaml
```

### Step 2: Generate Security Policy

```bash
node scripts/agent.js --action policy --spec openapi.yaml --output api-policy.json
```

### Step 3: Validate Implementation

```bash
node scripts/agent.js --action validate --spec openapi.yaml --gateway kong
```

## Detection

```yaml
title: Designing Secure Api Architecture Detection
id: c1124849-297f-4ac3-b623-154a8812b929
status: experimental
description: Detects suspicious activity related to designing secure api architecture techniques in security architecture context
logsource:
  category: network_connection
  product: firewall
detection:
  selection:
    DestinationPort: 443
    Initiated: "true"
  condition: selection
level: medium
tags:
  - attack.t1190
  - attack.lateral_movement
falsepositives:
  - Network segmentation testing by authorized infrastructure teams
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Designing Secure Api Architecture Detection | firewall/network_connection | Sigma rule (medium) |
| ATT&CK Coverage | MITRE ATT&CK | T1190 |

## Verification

- [ ] All endpoints require authentication (no anonymous access to sensitive data)
- [ ] OAuth 2.0 tokens validated with signature, expiry, audience, and scope checks
- [ ] Rate limiting enforced per client, per endpoint
- [ ] Request body validated against OpenAPI schema before processing
- [ ] API keys rotated on schedule and revocable
- [ ] GraphQL introspection disabled in production
- [ ] mTLS enforced for service-to-service communication
- [ ] API responses do not leak internal error details or stack traces

## References

- [OWASP API Security Top 10](https://owasp.org/API-Security/)
- [OAuth 2.0 Security Best Practices](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics)
- [OpenAPI Specification](https://spec.openapis.org/oas/latest.html)
