Skip to content

Chapter 13: API Security

Application Programming Interfaces are the connective tissue of modern software. REST, GraphQL, and gRPC APIs expose business logic and data to web clients, mobile apps, and partner integrations—making them a primary attack surface. This chapter surveys the OWASP API Security Top 10, examines SSRF in depth, and covers API design patterns that reduce risk.

13.1 REST API Security Principles

13.1.1 Authentication and Authorization

APIs authenticate callers using one of several credential types:

Credential Type Transport Notes
API Key Header / query param Simple; no expiry by default
Bearer Token (JWT) Authorization header Stateless; must verify signature
OAuth 2.0 Access Token Authorization header Scoped; short-lived
Mutual TLS (mTLS) TLS handshake Strong; client cert required
HMAC Signature Custom header Request integrity + auth

13.1.2 Rate Limiting

Rate limiting defends against brute-force, enumeration, and denial-of-service attacks. Common strategies include fixed-window, sliding-window, and token-bucket algorithms. Apply limits per user, per IP, and per endpoint.

Understanding the algorithm differences matters for choosing the right one. The token bucket algorithm maintains a conceptual bucket that fills with tokens at a fixed rate (e.g., 10 tokens per second) up to a maximum capacity. Each request consumes one token. If the bucket is empty, the request is rejected. The key property is that it allows bursts up to the bucket capacity while enforcing an average rate over time—a client can spend their whole bucket in a fraction of a second, which is useful for interactive applications that need occasional high-speed access but shouldn’t be able to sustain it. Implementations need only track two values per client: current token count and last refill timestamp.

The leaky bucket (or leaky bucket as a queue) enforces a strictly constant output rate regardless of input bursts. Incoming requests queue up, and the queue drains at a fixed rate. Excess requests that would overflow the queue are dropped. Leaky bucket smooths traffic completely, which suits network bandwidth shaping but can feel punishing for API users who expect to handle short bursts. For most REST APIs, token bucket is the better choice because it allows the burst headroom that legitimate clients need during page loads or batch operations.

The sliding window algorithm is a middle ground: it tracks requests across a rolling time window rather than a fixed one. Fixed windows have a well-known boundary attack where a client sends half their limit at the end of one window and half at the start of the next, doubling their effective rate at the boundary. Sliding windows close that gap. HTTP headers like X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset should always accompany rate limit responses so clients can backoff gracefully rather than hammering the server until they hit a 429.

13.2 OWASP API Security Top 10 (2023)

Definition 13.1 (OWASP API Security Top 10)

The OWASP API Security Top 10 (2023 edition) catalogues the most critical API vulnerabilities observed in production systems. Each entry describes a class of flaw, its exploitability, and recommended controls.

ID Name Description
API1 Broken Object Level Auth (BOLA) Accessing objects owned by other users
API2 Broken Authentication Weak credentials, missing MFA
API3 Broken Object Property Level Auth Exposing/updating sensitive fields
API4 Unrestricted Resource Consumption Missing rate limits; DoS
API5 Broken Function Level Auth (BFLA) Accessing admin functions as user
API6 Unrestricted Business Flows Bypassing workflow logic
API7 Server Side Request Forgery (SSRF) Fetching internal resources via API
API8 Security Misconfiguration Open CORS, verbose errors, debug on
API9 Improper Inventory Management Forgotten / shadow APIs
API10 Unsafe Consumption of Third-Party APIs Trusting external API output unsafely

13.2.1 BOLA (API1) and Mass Assignment (API3)

from flask import Flask, jsonify, g

app = Flask(__name__)

# VULNERABLE: BOLA - no ownership check
@app.route('/api/orders/<int:order_id>', methods=['GET'])
def get_order_vulnerable(order_id):
    order = db.find_order(order_id)        # Any user can fetch!
    return jsonify(order)

# SECURE: enforce object-level authorization
@app.route('/api/orders/<int:order_id>', methods=['GET'])
def get_order_secure(order_id):
    order = db.find_order(order_id)
    if order is None or order['user_id'] != g.current_user['id']:
        return jsonify({'error': 'Not found'}), 404
    return jsonify(order)

# VULNERABLE: Mass Assignment - client sets 'is_admin'
@app.route('/api/users/me', methods=['PUT'])
def update_user_vulnerable():
    data = request.get_json()
    db.update_user(g.current_user['id'], **data)  # Dangerous!
    return jsonify({'status': 'updated'})

# SECURE: allowlist updatable fields
UPDATABLE_FIELDS = {'display_name', 'email', 'bio'}

@app.route('/api/users/me', methods=['PUT'])
def update_user_secure():
    data = request.get_json()
    safe = {k: v for k, v in data.items() if k in UPDATABLE_FIELDS}
    db.update_user(g.current_user['id'], **safe)
    return jsonify({'status': 'updated'})

13.3 GraphQL Security

GraphQL’s flexibility introduces security challenges not present in REST APIs. Where REST exposes a fixed set of endpoints with defined shapes, GraphQL lets clients compose arbitrary queries, which shifts the surface area in ways that catch developers off-guard.

GraphQL Introspection Disclosure

GraphQL introspection allows clients to query the full schema. In production, introspection should be disabled or restricted to authenticated users—it reveals all types, fields, and mutations to an attacker doing reconnaissance.

Introspection abuse is frequently the first step of a GraphQL attack, not the attack itself. An attacker issues an introspection query to get the full schema, then examines it for hidden or undocumented mutations (like updateUserRole), fields marked as admin-only in comments but not actually guarded by authorization checks, and relationships between types that suggest BOLA opportunities. Tools like graphql-voyager and InQL visualise and scan GraphQL schemas automatically. Disabling introspection makes reconnaissance harder but doesn’t fix authorization holes—a determined attacker will fuzz field names from common conventions anyway. So disable introspection and fix authorization; don’t treat them as alternatives.

GraphQL DoS via Deep Nesting

GraphQL allows recursive queries. An attacker submits a deeply nested query that causes exponential resolver calls: { user { friends { friends { friends {...} } } } }. Defences: enforce maximum query depth (e.g., 10 levels), maximum query complexity, and query timeout.

Depth limiting alone isn’t sufficient because a query can be wide instead of deep: requesting a hundred top-level fields or a list of a million items via first: 1000000 both cause server-side exhaustion without deep nesting. A proper defence assigns a cost score to each field and list argument—a field costs 1, and a paginated list multiplies the field cost by the requested page size—and rejects queries whose total complexity exceeds a threshold before any resolvers run. The graphql-cost-analysis and graphql-query-complexity libraries implement this pattern. Aliases are another GraphQL feature that multiplies work: alias1: expensiveField, alias2: expensiveField, ... evaluates the same expensive resolver many times under different names, potentially bypassing naive per-field rate limits.

13.4 REST vs GraphQL vs gRPC Security Comparison

Property REST GraphQL gRPC
Auth mechanism JWT / OAuth2 / API key JWT / OAuth2 mTLS / OAuth2
Input validation Schema (OpenAPI) Schema + custom rules Protobuf types
BOLA risk High (path params) High (resolver args) Medium
Introspection OpenAPI optional Enabled by default Reflection optional
DoS via query complexity Low High (nested queries) Medium (streaming)
Transport HTTP/1.1 or HTTP/2 HTTP/1.1 or HTTP/2 HTTP/2 only
Rate limiting Standard Per-query complexity Per-RPC or streaming
Error verbosity Configurable Errors in JSON body gRPC status codes

13.5 API Gateway Security

Definition 13.2 (API Gateway)

An API gateway is a reverse proxy that centralises cross-cutting concerns: authentication, rate limiting, TLS termination, request logging, and routing. Examples include AWS API Gateway, Kong, Apigee, and Nginx.

image

The gateway enforces: IP allowlisting, JWT signature validation (delegating to the IDP), request size limits, and per-client rate limits. Backend services trust only requests arriving via the gateway and verify the forwarded identity claim.

13.6 Server-Side Request Forgery (SSRF)

Definition 13.3 (SSRF)

Server-Side Request Forgery (SSRF) occurs when an attacker can cause the server to issue HTTP requests to an attacker-controlled destination. The server’s network position gives access to internal services, cloud metadata endpoints, and localhost ports inaccessible to the attacker directly.

13.6.1 AWS IMDSv1 Exploitation

SSRF to AWS Instance Metadata

The AWS EC2 Instance Metadata Service (IMDSv1) is accessible at 169.254.169.254. An SSRF vulnerability lets an attacker steal IAM credentials:

# Attacker-controlled payload --- server fetches this URL
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Returns: role name, then:
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/MyRole
# Returns: AccessKeyId, SecretAccessKey, Token (valid ~6 hours)

Mitigations: enforce IMDSv2 (token-required PUT before GET); block 169.254.0.0/16 in egress firewall; use instance profiles only when needed.

13.6.2 SSRF Filter Bypasses

Naive SSRF filters block strings like 169.254.169.254 but can be bypassed:

Bypass Technique Example
Decimal IP http://2852039166/
Octal IP http://0251.0376.0251.0376/
IPv6 loopback http://[::1]/
IPv6 mapped http://[::ffff:169.254.169.254]/
DNS rebinding Resolve to public IP; rotate to internal
URL redirect https://trusted.example/?url=http://internal/

Defence: use an allowlist of permitted egress destinations; resolve and validate the IP after DNS resolution; reject private RFC 1918 and link-local ranges.

DNS rebinding is the most dangerous SSRF filter bypass and the one most commonly missed. The attack works in two phases. First, the attacker’s domain resolves to a legitimate public IP (to pass the server’s allowlist or IP blocklist check). The server fetches the URL, the DNS response is cached, and everything looks fine. Second, after a very short TTL expires, the attacker’s DNS server rotates the same domain to resolve to 127.0.0.1 or an internal IP. When the server makes a follow-up request—or even on retry after a redirect—the hostname now resolves to the internal address. Naive SSRF defences that check the hostname at request construction time are vulnerable; the correct fix is to resolve the hostname to an IP, check that IP against the blocklist, then make the connection to that specific IP rather than re-resolving the hostname.

Cloud metadata endpoints deserve special mention because the consequences of reaching them are so severe. AWS IMDSv2 requires a PUT request with a custom header to obtain a session token before the metadata service will respond—a pure GET-based SSRF can’t satisfy this requirement. GCP metadata at http://metadata.google.internal/ is protected by a required Metadata-Flavor: Google header. Azure IMDS at http://169.254.169.254/metadata/instance requires Metadata: true. Critically, these required headers must be set by the attacker through the SSRF vector, which means SSRF via a simple URL fetch (image fetcher, PDF generator, webhook tester) can only reach the older, unprotected IMDSv1 endpoints. IMDSv1 must be explicitly disabled—it’s off by default on new AWS accounts, but many existing deployments still have it enabled from before that change.

13.7 API Key Management and HMAC Signing

13.7.1 API Key Best Practices

API Key Hygiene

  • Scope keys to minimum required permissions (least privilege).

  • Store keys in a secrets manager (AWS Secrets Manager, HashiCorp Vault), never in source code or environment variables of shared systems.

  • Rotate keys automatically on a defined schedule and immediately on suspected exposure.

  • Log every API key usage with timestamp and source IP.

13.7.2 HMAC Request Signing

AWS Signature Version 4 style signing authenticates every request, preventing replay attacks via a request timestamp and verifying request integrity.

import hmac, hashlib, datetime

def sign_request(method, path, body, secret_key, access_key):
    timestamp = datetime.datetime.utcnow().strftime('
    date_stamp = timestamp[:8]

    # Canonical request
    payload_hash = hashlib.sha256(body.encode()).hexdigest()
    canonical = f"{method}\n{path}\n\n" \
                f"host:api.example.com\nx-amz-date:{timestamp}\n\n" \
                f"host;x-amz-date\n{payload_hash}"

    # String to sign
    string_to_sign = (f"AWS4-HMAC-SHA256\n{timestamp}\n"
                      f"{date_stamp}/us-east-1/execute-api/aws4_request\n"
                      + hashlib.sha256(canonical.encode()).hexdigest())

    # Derived signing key
    def hmac_sha256(key, data):
        return hmac.new(key, data.encode(), hashlib.sha256).digest()

    signing_key = hmac_sha256(
        hmac_sha256(
            hmac_sha256(
                hmac_sha256(f"AWS4{secret_key}".encode(), date_stamp),
                'us-east-1'),
            'execute-api'),
        'aws4_request')

    signature = hmac.new(signing_key,
                         string_to_sign.encode(),
                         hashlib.sha256).hexdigest()
    return timestamp, signature

13.8 Python FastAPI: JWT Bearer Authentication

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt   # PyJWT

app = FastAPI()
bearer_scheme = HTTPBearer()
PUBLIC_KEY = open('rsa_public.pem').read()
ALGORITHM = 'RS256'          # Pin algorithm --- never read from token

def get_current_user(
    creds: HTTPAuthorizationCredentials = Depends(bearer_scheme)
):
    token = creds.credentials
    try:
        payload = jwt.decode(token, PUBLIC_KEY,
                             algorithms=[ALGORITHM],
                             audience='my-api')
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail='Token expired')
    except jwt.InvalidTokenError as e:
        raise HTTPException(status_code=401, detail=str(e))
    return payload

@app.get('/api/profile')
def read_profile(user = Depends(get_current_user)):
    return {'sub': user['sub'], 'email': user.get('email')}

13.9 Exercises

Exercise 13.1

Design a rate limiting strategy for a public REST API that serves both anonymous users and authenticated users. Specify: (a) the rate limit tiers (requests per minute) for each user class; (b) how you identify anonymous users fairly without exposing fingerprinting privacy risks; (c) how the API communicates rate-limit status to clients (HTTP headers); (d) the algorithm (token bucket vs sliding window) and your justification.

Exercise 13.2

A developer presents the following API endpoint for code review: GET /api/admin/users?role=admin. The endpoint requires a JWT but does not check the user’s role. Identify which OWASP API Security category applies, explain the impact, and rewrite the endpoint handler in Python (Flask or FastAPI) to fix the vulnerability.

Exercise 13.3

Explain the SSRF attack chain from initial vulnerability to IAM credential theft on AWS. For each step, state the attacker’s action and the server’s response. Then describe three independent controls that would break the chain at different points.

Exercise 13.4

A GraphQL API exposes a Post type with a comments field, which itself has a replies field, which has a comments field, and so on. Write the most destructive query an attacker could submit. Calculate the number of resolver invocations for depth \(d\) if each node has \(n\) children. Propose a query complexity scoring formula and a safe maximum complexity threshold.

Exercise 13.5

Review the HMAC signing code in Section 13. (a) What attack does the timestamp prevent? (b) What is the recommended clock skew tolerance? (c) If the x-amz-date header is omitted from the signed headers, what new attack becomes possible? (d) How does AWS SigV4 protect against a path traversal attack via the canonical request?