Back
+25 XP
Concept

API Gateway Pattern: Reverse Proxying & Header Sanitization

Exposing internal microservices directly to the public web creates massive attack surfaces. An API Gateway functions as a reverse proxy shield: stripping forbidden hop-by-hop headers, filtering spoofed internal claims (`X-Internal-Role`), injecting verified identities, and appending canonical `X-Forwarded-For` chains 🚪🛡️🌐.

python
STRIP_HEADERS = {"connection", "upgrade", "x-internal-user", "x-admin"}

def sanitize_edge_headers(headers, client_ip):
    clean = {k: v for k, v in headers.items() if k.lower() not in STRIP_HEADERS}
    xff = clean.get("X-Forwarded-For")
    clean["X-Forwarded-For"] = f"{xff}, {client_ip}" if xff else client_ip
    return clean

raw = {"Host": "xicae.org", "X-Internal-User": "root", "Accept": "*/*"}
safe = sanitize_edge_headers(raw, "203.0.113.1")
print("Sanitized Edge Headers:", safe)

# 102. API Gateway Pattern: Reverse Proxying & Header Sanitization Microservices within a private cloud network often assume that any request arriving at their internal port has already passed authentication. If external clients can send arbitrary HTTP headers directly to these microservices, attackers can forge identities effortlessly 🛑. ```python # The Spoofing Vulnerability: # Malicious Client sends: # GET /api/v1/delete_database HTTP/1.1 # Host: api.example.com # X-Internal-Role: superadmin <-- Spoofed Header! # # If downstream microservice trusts X-Internal-Role, system is breached! ``` ### Gateway Armor Architecture 1. **Header Stripping (Deny List & Allow List)**: Strip all RFC 2616 / RFC 7230 hop-by-hop headers (`Connection`, `Keep-Alive`, `Upgrade`, `Transfer-Encoding`) and strip any header starting with your internal security prefix (`X-Internal-*`). 2. **Deterministic Context Injection**: After the API Gateway verifies the client's JWT or mTLS certificate, it generates and attaches clean, cryptographic internal headers for downstream consumption. 3. **Trace & Provenance Tracking**: Append client remote IP to the `X-Forwarded-For` chain and inject the root W3C `traceparent` header to guarantee complete auditability 🛡️⚡. --- ### Interactive Pop-Quiz 🧠 #### Why must an API Gateway strip client-supplied headers like X-Internal-Role before proxying requests to downstream services? - [ ] To prevent privilege escalation attacks where malicious clients spoof internal authorization credentials that downstreams blindly trust 🛡️ - [ ] Because HTTP 2.0 prohibits custom header names - [ ] To reduce JSON serialization overhead on the CPU - [ ] Because the Linux kernel crashes if headers exceed 10 characters --- ### Practical Challenge 🎯 Implement `GatewayProxy.sanitize_headers(incoming: dict[str, str], client_ip: str) -> dict[str, str]` that filters out case-insensitive RFC hop-by-hop headers (`connection`, `upgrade`, `keep-alive`, `transfer-encoding`) and internal headers (`x-internal-role`, `x-internal-user-id`), then appends `client_ip` to `'X-Forwarded-For'`. Verify header stripping and forwarding chain, and print the sanitized dictionary. <details> <summary>Solution</summary> ```python HOP_BY_HOP = {"connection", "keep-alive", "transfer-encoding", "upgrade"} INTERNAL_RESTRICTED = {"x-internal-role", "x-internal-user-id"} class GatewayProxy: @staticmethod def sanitize_headers(incoming: dict[str, str], client_ip: str) -> dict[str, str]: sanitized = {} for k, v in incoming.items(): lower = k.lower() if lower in HOP_BY_HOP or lower in INTERNAL_RESTRICTED: continue sanitized[k] = v existing_xff = sanitized.get("X-Forwarded-For") if existing_xff: sanitized["X-Forwarded-For"] = f"{existing_xff}, {client_ip}" else: sanitized["X-Forwarded-For"] = client_ip return sanitized raw_headers = { "Host": "api.production.internal", "Connection": "keep-alive", "Upgrade": "websocket", "X-Internal-Role": "admin_root", "X-Custom-Auth": "bearer-token-123" } clean = GatewayProxy.sanitize_headers(raw_headers, "198.51.100.42") assert "Connection" not in clean assert "Upgrade" not in clean assert "X-Internal-Role" not in clean assert clean["X-Custom-Auth"] == "bearer-token-123" assert clean["X-Forwarded-For"] == "198.51.100.42" print(f"Sanitized headers: {clean}") ``` </details>

Checkpoint

Why must an API Gateway strip client-supplied headers like `X-Internal-Role` before proxying requests to downstream services? 🧠

Practice

Implement `GatewayProxy.sanitize_headers(incoming: dict[str, str], client_ip: str) -> dict[str, str]` that filters out case-insensitive RFC hop-by-hop headers (`connection`, `upgrade`, `keep-alive`, `transfer-encoding`) and internal headers (`x-internal-role`, `x-internal-user-id`), then appends `client_ip` to `'X-Forwarded-For'`. Verify header stripping and forwarding chain, and print the sanitized dictionary. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks