Develop a policy-driven API gateway pipeline injecting authentication, schema…
- User
Develop a policy-driven API gateway pipeline injecting authentication, schema validation, and transformation steps.
Assistant
Develop a policy-driven API gateway pipeline injecting authentication, schema validation, and transformation steps.
The user wants a "policy-driven API gateway pipeline". The goal is to demonstrate how to inject steps like authentication, schema validation, and transformation into the request processing flow based on policies.
Core Concepts:
Language/Stack Selection:
I will choose Golang because it is the de facto standard for modern cloud-native API gateways. Its interface structure fits the "Pipeline" pattern perfectly.
Architecture Design:
func(ctx context.Context, req Request) (Response, error).Step-by-Step Implementation Plan:
Request, Response, and Context.Middleware type.auth: jwt, validate: true).Refining the "Policy-Driven" aspect:
Instead of hardcoding the chain, the main handler should look at a configuration map.
Example Config:
/users: [Auth, Transform]
/public: [Log]
Drafting the Code (Mental or Scratchpad):
http.Request or create a custom context struct.Middleware.type Middleware func(ctx *Context) error
func BuildPipeline(policies []Policy) []Middleware {
// iterate policies, append middlewares
}
Detailed Logic for Steps:
Authorization header. If missing, return 401. If present, set ctx.UserID.email field exists. If not, return 400.X-Processed-By: Gateway. Rename a field in JSON (e.g., id -> user_id).Edge Cases/Production concerns to mention:
Writing the solution: I will provide a complete, runnable Go program. It's the best way to demonstrate the architecture.
Context struct (holds request data and "baggage" like User info).Handler interface.AuthHandler, ValidationHandler, TransformHandler).Pipeline struct (holds the chain).Factory that builds pipelines based on a config map.main function serving requests.Self-Correction during drafting:
Handling request bodies in a pipeline is tricky because io.Reader is one-time read. I need to read the body into a byte slice in the context so multiple steps can access it.
Let's refine the schema validation. Implementing a full JSON Schema validator from scratch is too much code. I will implement a "Validator" interface and a simple "Required Field Validator" implementation.
Final Code Structure:
GatewayContext, Middleware.PolicyConfig).http.Handler wrapper.Let's write the code.
Imports: net/http, encoding/json, context, strings, io.
Context: Holds http.Request, ResponseWriter (or a buffer for response), and a map for passing data between steps. Actually, modifying the response is usually done at the end, but for request transformation, we modify the request body buffer.
Auth Step: Check header.
Validation Step: Parse JSON, check fields.
Transform Step: Parse JSON, modify, re-encode.
Outcome: A clean, extensible example showing how requests flow through a dynamically constructed chain.
I will also explain the "Policy" aspect clearly—how this allows changing behavior without changing code, just configuration.
Let's prepare the Go code.
Code Blocks:
This looks solid. I will ensure the code is well-commented. I will focus on the interceptor pattern.
One specific detail: "Policy-driven". This usually implies a configuration format.
I will define a ServiceConfig struct that maps paths to lists of policies.
e.g.,
type ServiceConfig struct {
Path string
Policies []string
}
And a registry:
var policyRegistry = map[string]MiddlewareFactory{...}
This ensures I hit the requirement of "Policy-driven".
Let's proceed. A policy-driven API gateway decouples the routing logic from the "cross-cutting concerns" (security, validation, transformation). Instead of hardcoding these steps, we define a "Pipeline" based on configuration (policies) attached to specific routes.
Below is a complete, runnable proof-of-concept in Go (Golang). Go is ideal for this because its HandlerFunc interface naturally supports the Chain of Responsibility pattern used in gateway pipelines.
Auth step extracts a User ID, which the Transform step later uses).Save this code into a file named main.go.
Configuration (PolicyConfig):
The policies slice in main() acts as your configuration source. In a real-world scenario, this would come from a database or YAML/JSON files. It defines the /api/users endpoint as requiring auth, validation, transform, and proxy.
The Pipeline Factory (BuildPipeline):
The gateway looks at the Policies string array (["auth", "validation"...]) and constructs an array of function references ([]Step). This makes the system data-driven. You can change the order or add steps by changing data, not code.
Execution Flow:
Authorization header. If it fails, it sets ctx.Abort = true. The loop breaks immediately, returning 401.r.Body is a stream, it reads it into ctx.RequestBody so the Proxy step can read it again later. It checks JSON validity.X-User-ID header based on the token verification from step 1.httpbin.org (a standard echo service) and pipes the response back.1. Failure Case (Missing Auth)
curl -X POST http://localhost:8080/api/users
# Output: Invalid or missing API Token
2. Failure Case (Schema Validation)
curl -X POST http://localhost:8080/api/users \
-H "Authorization: Bearer secret-token" \
-H "Content-Type: application/json" \
-d '{"wrong": "field"}'
# Output: Schema Error: Missing required field 'data'
3. Success Case
curl -X POST http://localhost:8080/api/users \
-H "Authorization: Bearer secret-token" \
-H "Content-Type: application/json" \
-d '{"data": "value"}'
# Output: JSON response from httpbin.org showing headers (including X-User-Id) and body
.so files for new policies without restarting the gateway.AuthStep with a generic OpaStep that queries an external OPA server for policy decisions.CircuitBreakerStep that checks the health of the backend before attempting ProxyStep.package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
)
// ==========================================
// 1. Domain & Context Models
// ==========================================
// GatewayContext carries state through the pipeline
type GatewayContext struct {
W http.ResponseWriter
R *http.Request
Abort bool // If true, stop processing the pipeline
Status int
Error string
// Custom data sharing between steps
UserID string
RequestBody []byte // Buffer for body inspection/modification
}
// PolicyConfig defines the pipeline for a specific path
type PolicyConfig struct {
Path string `json:"path"`
Methods []string `json:"methods"`
Policies []string `json:"policies"` // Ordered list of steps
TargetURL string `json:"target_url"` // Backend service
Schema json.RawMessage `json:"schema"` // Validation schema
Transforms map[string]string `json:"transforms"` // Header mappings
}
// ==========================================
// 2. Pipeline Step Interface
// ==========================================
// Step is a single unit of logic in the gateway
type Step func(ctx *GatewayContext) error
// StepFactory creates steps based on configuration
type StepFactory func(config PolicyConfig) Step
// ==========================================
// 3. Policy Implementations
// ==========================================
// Policy: Authentication
// Checks for a hardcoded Bearer token (Simplified)
func AuthStep(config PolicyConfig) Step {
return func(ctx *GatewayContext) error {
token := ctx.R.Header.Get("Authorization")
// Mock logic: In reality, verify JWT or call Auth0/Keycloak
if token != "Bearer secret-token" {
ctx.Abort = true
ctx.Status = http.StatusUnauthorized
ctx.Error = "Invalid or missing API Token"
return fmt.Errorf("auth failed")
}
// Share data with downstream steps
ctx.UserID = "user-123-from-token"
log.Printf("[Pipeline] ✅ Auth Passed for %s", ctx.R.URL.Path)
return nil
}
}
// Policy: Schema Validation
// Ensures JSON body is present (Simplified)
func ValidationStep(config PolicyConfig) Step {
return func(ctx *GatewayContext) error {
// Only validate if Content-Type is JSON
if !strings.Contains(ctx.R.Header.Get("Content-Type"), "application/json") {
return nil // Skip validation for non-json
}
// Read body into buffer so we can reuse it
body, err := io.ReadAll(ctx.R.Body)
if err != nil {
ctx.Abort = true
ctx.Status = http.StatusBadRequest
return err
}
ctx.RequestBody = body
ctx.R.Body = io.NopCloser(bytes.NewBuffer(body)) // Reset standard body reader
// Mock Validation: Check if body is valid JSON and contains a 'data' field
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err != nil {
ctx.Abort = true
ctx.Status = http.StatusBadRequest
ctx.Error = "Invalid JSON payload"
return err
}
if _, ok := payload["data"]; !ok {
ctx.Abort = true
ctx.Status = http.StatusBadRequest
ctx.Error = "Schema Error: Missing required field 'data'"
return fmt.Errorf("schema validation failed")
}
log.Printf("[Pipeline] ✅ Validation Passed")
return nil
}
}
// Policy: Transformation
// Injects headers for the backend service
func TransformStep(config PolicyConfig) Step {
return func(ctx *GatewayContext) error {
// Example: Inject User ID into headers for the backend
if ctx.UserID != "" {
ctx.R.Header.Set("X-User-ID", ctx.UserID)
}
// Example: Strip the gateway path prefix before sending to backend
// (Usually handled by proxy logic, but logic sits here conceptually)
log.Printf("[Pipeline] ✅ Transformation: Injected X-User-ID")
return nil
}
}
// Policy: Proxy (Final Step)
// Forwards request to backend
func ProxyStep(config PolicyConfig) Step {
return func(ctx *GatewayContext) error {
log.Printf("[Pipeline] 🚀 Proxying request to %s", config.TargetURL)
// Construct backend URL
targetPath := config.TargetURL + ctx.R.URL.Path
// Recreate body reader if we buffered it, otherwise use original
var bodyReader io.Reader
if ctx.RequestBody != nil {
bodyReader = bytes.NewBuffer(ctx.RequestBody)
} else {
bodyReader = ctx.R.Body
}
proxyReq, err := http.NewRequest(ctx.R.Method, targetPath, bodyReader)
if err != nil {
return err
}
// Copy headers
proxyReq.Header = ctx.R.Header
client := &http.Client{}
resp, err := client.Do(proxyReq)
if err != nil {
ctx.Abort = true
ctx.Status = http.StatusBadGateway
ctx.Error = "Backend unreachable"
return err
}
defer resp.Body.Close()
// Copy response back to client
ctx.Status = resp.StatusCode
for k, v := range resp.Header {
ctx.W.Header()[k] = v
}
io.Copy(ctx.W, resp.Body)
ctx.Abort = true // End of pipeline
return nil
}
}
// ==========================================
// 4. Pipeline Engine & Factory
// ==========================================
type GatewayEngine struct {
Routes map[string]PolicyConfig
}
func NewGatewayEngine() *GatewayEngine {
return &GatewayEngine{Routes: make(map[string]PolicyConfig)}
}
func (g *GatewayEngine) LoadConfig(configs []PolicyConfig) {
for _, c := range configs {
g.Routes[c.Path] = c
}
}
// BuildPipeline creates the chain of steps dynamically
func (g *GatewayEngine) BuildPipeline(routeConfig PolicyConfig) []Step {
var pipeline []Step
// Map string names from config to actual Step functions
for _, policyName := range routeConfig.Policies {
switch policyName {
case "auth":
pipeline = append(pipeline, AuthStep(routeConfig))
case "validation":
pipeline = append(pipeline, ValidationStep(routeConfig))
case "transform":
pipeline = append(pipeline, TransformStep(routeConfig))
case "proxy":
pipeline = append(pipeline, ProxyStep(routeConfig))
default:
log.Printf("Warning: Unknown policy '%s'", policyName)
}
}
return pipeline
}
func (g *GatewayEngine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 1. Route Matching
config, exists := g.Routes[r.URL.Path]
if !exists {
http.NotFound(w, r)
return
}
// 2. Method Check (Basic)
validMethod := false
for _, m := range config.Methods {
if m == r.Method {
validMethod = true
break
}
}
if !validMethod {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
// 3. Build and Execute Pipeline
pipeline := g.BuildPipeline(config)
ctx := &GatewayContext{
W: w,
R: r,
Status: http.StatusOK,
}
for _, step := range pipeline {
err := step(ctx)
if ctx.Abort {
// If an error occurred and we haven't written headers yet (e.g. before proxy)
if err != nil && ctx.Status >= 400 {
http.Error(w, ctx.Error, ctx.Status)
}
break
}
}
}
// ==========================================
// 5. Main Execution
// ==========================================
func main() {
// Define Policy Configuration (Mock DB/JSON Load)
policies := []PolicyConfig{
{
Path: "/api/users",
Methods: []string{"POST"},
TargetURL: "https://httpbin.org/post", // Public mock backend
Policies: []string{"auth", "validation", "transform", "proxy"},
},
{
Path: "/api/public",
Methods: []string{"GET"},
TargetURL: "https://httpbin.org/get",
Policies: []string{"proxy"}, // No auth, no validation
},
}
// Initialize Gateway
gw := NewGatewayEngine()
gw.LoadConfig(policies)
port := ":8080"
fmt.Printf("🚀 API Gateway running on %s\n", port)
fmt.Println("---------------------------------------------------")
fmt.Println("Test 1 (Fail): curl -X POST http://localhost:8080/api/users")
fmt.Println("Test 2 (Pass): curl -X POST -H \"Authorization: Bearer secret-token\" -H \"Content-Type: application/json\" -d '{\"data\":\"value\"}' http://localhost:8080/api/users")
log.Fatal(http.ListenAndServe(port, gw))
}