Back
+30 XP
Concept

Gauntlet 12: Reverse Proxy Gateway

API gateways like Kong and Envoy shield internal microservices behind a unified public domain. A reverse proxy matches incoming URL prefixes, rewrites path paths for upstream services, enriches headers with tracing IDs and client IPs, and forwards responses transparently.

python
# Header enrichment:
headers['x-forwarded-for'] = client_ip
headers['x-request-id'] = str(uuid.uuid4())
# Path rewrite:
upstream_path = rewrite_prefix + path[len(match_prefix):]

# Gauntlet 12: Reverse Proxy Gateway with Path Rewriting & Headers In production architectures, internal microservices are never exposed directly to the public internet. An **API Gateway / Reverse Proxy** (like Nginx, Envoy, or Traefik) sits on the boundary: 🛡️🌐 1. **Path Rewriting**: External users call `https://api.xicae.com/billing/checkout`. The proxy strips `/billing` and routes to internal service `http://billing-svc.internal:8000/v2/checkout`. 2. **Header Enrichment**: Because the backend socket connection comes from the proxy itself, the backend loses the user's real IP. The proxy injects: - `X-Forwarded-For: <client_ip>` - `X-Forwarded-Proto: https` - `X-Request-ID: <uuid>` (for distributed tracing across logs). 3. **Graceful Failover**: Returns `502 Bad Gateway` if no matching upstream route exists. ```python import uuid # Enriched proxy headers: headers["x-forwarded-for"] = client_ip headers["x-request-id"] = str(uuid.uuid4()) ``` ## Pop Quiz Why do reverse proxies append client IP addresses to the `X-Forwarded-For` header? - [ ] The upstream backend sees the proxy's IP as the socket peer; X-Forwarded-For preserves the real client origin IP address. - [ ] To allow network switches to execute BGP routing tables in userspace. - [ ] X-Forwarded-For encrypts internal network traffic with TLS certificates. - [ ] Because upstream web servers reject requests that lack geographical GPS coordinates. ## Real-World Challenge Implement `ReverseProxyGateway`: - `add_route(prefix: str, rewrite_prefix: str, backend_callable)`: Registers routing rule. - `handle_request(method: str, path: str, headers: dict, body: bytes, client_ip: str) -> dict`: - Matches route by path prefix. - Rewrites target path: `rewrite_prefix + path[len(prefix):]`. - Injects `x-forwarded-for`, `x-forwarded-proto: https`, and a unique `x-request-id`. - Dispatches to `backend_callable(method, new_path, new_headers, body)`. - Returns `{"status": 502, ...}` if no matching route is found. <details> <summary>Solution</summary> ```python import uuid class ReverseProxyGateway: def __init__(self): self._routes = [] # list of (prefix, rewrite_prefix, backend_fn) def add_route(self, prefix: str, rewrite_prefix: str, backend_callable): self._routes.append((prefix, rewrite_prefix, backend_callable)) def handle_request( self, method: str, path: str, headers: dict, body: bytes, client_ip: str ) -> dict: matched_rule = None for prefix, rewrite_prefix, backend_fn in self._routes: if path.startswith(prefix): matched_rule = (prefix, rewrite_prefix, backend_fn) break if not matched_rule: return { "status": 502, "headers": {"content-type": "text/plain"}, "body": b"Bad Gateway: No Upstream Route Configured" } prefix, rewrite_prefix, backend_fn = matched_rule # 1. Path rewriting rewritten_path = rewrite_prefix + path[len(prefix):] # 2. Header enrichment enriched = dict(headers) enriched["x-forwarded-for"] = client_ip enriched["x-forwarded-proto"] = "https" if "x-request-id" not in enriched: enriched["x-request-id"] = str(uuid.uuid4()) # 3. Upstream dispatch return backend_fn(method.upper(), rewritten_path, enriched, body) # Verification gateway = ReverseProxyGateway() # Upstream mock service def auth_microservice(method, path, headers, body): return { "status": 200, "headers": {"content-type": "application/json"}, "body": f"ACK:{path}:{headers['x-forwarded-for']}".encode("utf-8") } gateway.add_route("/api/auth", "/v1/auth", auth_microservice) # 1. Route match and rewrite test res = gateway.handle_request("POST", "/api/auth/login", {}, b"credentials", client_ip="203.0.113.19") assert res["status"] == 200 assert res["body"] == b"ACK:/v1/auth/login:203.0.113.19" # 2. Unmatched route 502 test res_unmatched = gateway.handle_request("GET", "/unknown/route", {}, b"", client_ip="127.0.0.1") assert res_unmatched["status"] == 502 ``` </details>