X-ITM Insight

Building a Secure and Scalable Gateway API with Envoy and Coraza WAF: A Practical Guide

Learn how to architect, deploy, and integrate a Gateway API using Envoy and Coraza WAF alongside NGINX ingress for secure, high-performance API gateways. This guide covers best practices, challenges, and practical steps for implementation.

Building a Secure and Scalable Gateway API with Envoy and Coraza WAF

Modern applications rely heavily on APIs to expose functionality, integrate services, and enable seamless interactions between systems. However, securing these APIs while ensuring high performance, scalability, and reliability is a complex challenge. This guide explores how to architect, deploy, and integrate a Gateway API using Envoy and Coraza WAF alongside NGINX ingress, addressing common pain points encountered in production environments.

Why a Gateway API?

A Gateway API acts as a single entry point for client requests, routing them to the appropriate backend services while handling security, rate limiting, authentication, and other cross-cutting concerns. By consolidating these responsibilities, a Gateway API simplifies architecture, improves security, and enhances performance.

Envoy, a high-performance proxy developed by Lyft, and Coraza WAF, a Web Application Firewall (WAF) built on top of OpenResty’s LuaJIT, provide powerful tools to achieve these goals. When combined with NGINX for ingress, they create a robust, layered approach to API management.

Architectural Considerations

1. Layered Architecture

A well-designed Gateway API architecture typically consists of multiple layers:

  • Client Layer: Handles incoming requests from users or other services.
  • Ingress Layer (NGINX): Manages initial request routing, load balancing, and basic security policies.
  • API Gateway Layer (Envoy): Routes requests to backend services, enforces policies, and handles service discovery.
  • Security Layer (Coraza WAF): Protects against common web vulnerabilities like SQL injection, XSS, and DDoS attacks.
  • Backend Services Layer: The actual services or applications being exposed via the API.

2. Key Components

– **Envoy**: Acts as a reverse proxy and load balancer. It supports dynamic configuration, health checks, and advanced traffic management features.
– **Coraza WAF**: Integrates with Envoy to provide WAF capabilities, leveraging ModSecurity’s ruleset for security enforcement.
– **NGINX**: Often used for static content serving, basic load balancing, and initial request handling before passing traffic to Envoy.

Step-by-Step Implementation

Step 1: Set Up NGINX Ingress

NGINX can serve as the initial ingress point, handling static content and routing dynamic requests to Envoy. Below is a basic NGINX configuration example:

“`nginx
server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://envoy:9901;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
“`

In this setup, NGINX forwards all requests to Envoy running on port `9901`. Ensure NGINX is configured to handle SSL termination if required, using Let’s Encrypt or a dedicated certificate authority.

Step 2: Deploy Envoy as a Service Mesh Proxy

Envoy can be deployed as a sidecar proxy or a standalone service. For a Gateway API, a standalone deployment is often preferred. Below is a basic Docker Compose snippet to deploy Envoy:

“`yaml
docker-compose.yml
services:
envoy:
image: envoyproxy/envoy:v1.26-latest
ports:
– “9901:9901”
volumes:
– ./envoy.yaml:/etc/envoy/envoy.yaml
command: [“-c”, “/etc/envoy/envoy.yaml”]
“`

The core configuration (`envoy.yaml`) defines routes, filters, and service discovery. Here’s a minimal example:

“`yaml
static_resources:
listeners:
– name: listener_0
address:
socket_address:
address: 0.0.0.0
port_value: 9901
filter_chains:
– filters:
– name: envoy.filters.network.http_connection_manager
typed_config:
“@type”: type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
codec_type: auto
stat_prefix: ingress_http
route_config:
name: local_route
virtual_hosts:
– name: local_service
domains: [“*”]
routes:
– match:
prefix: /
route:
cluster: backend_service
max_stream_duration:
grpc_timeout_header_max: 0s
http_filters:
– name: envoy.filters.http.router

clusters:
– name: backend_service
connect_timeout: 0.25s
type: logical_dns
http2_protocol_options: {}
lb_policy: round_robin
load_assignment:
cluster_name: backend_service
endpoints:
– lb_endpoints:
– endpoint:
address:
socket_address:
address: backend-service
port_value: 8080
“`

This configuration routes all requests to a backend service running on `backend-service:8080`. Adjust the `cluster` and `route` configurations based on your backend services.

Step 3: Integrate Coraza WAF with Envoy

Coraza WAF provides ModSecurity rules for Envoy, allowing you to enforce security policies directly in the proxy layer. To integrate Coraza with Envoy, you’ll need to:

1. **Enable Lua Support in Envoy**: Envoy must be compiled with Lua support enabled. If using a pre-built image, ensure it includes Lua.
2. **Configure Coraza in Envoy**: Add the Coraza filter to your Envoy configuration.

Below is an updated `envoy.yaml` snippet with Coraza integration:

“`yaml
http_filters:
– name: envoy.filters.http.lua
typed_config:
“@type”: type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
local coraza = require “coraza”
local ctx = coraza.new()
ctx:init()
ctx:setvar(“REQUEST_FILENAME”, request_handle:headers():get(“:path”))
ctx:reqstart()
ctx:reqheader(“GET”, “”, “”, “”, “”, “”)
ctx:reqbody()
ctx:reqend()
local ok, err = ctx:process()
if not ok then
request_handle:streamInfo():closeStream(“Coraza WAF blocked request: ” .. err)
return
end
end
– name: envoy.filters.http.router
“`

This snippet demonstrates a basic Coraza integration. For production use, you’ll need to:

– Load ModSecurity rules (e.g., OWASP Core Rule Set).
– Configure logging and alerting for blocked requests.
– Fine-tune rules to avoid false positives.

Step 4: Deploy and Test

1. **Deploy NGINX and Envoy**: Use your preferred orchestration tool (e.g., Kubernetes, Docker Swarm) to deploy NGINX and Envoy.
2. **Verify Connectivity**: Ensure NGINX can forward requests to Envoy and that Envoy can route requests to backend services.
3. **Test Security Policies**: Send test requests to trigger Coraza WAF rules and verify that blocked requests are handled correctly.
4. **Monitor Performance**: Use tools like Prometheus and Grafana to monitor latency, error rates, and resource usage.

Step 5: Scale and Optimize

– **Horizontal Scaling**: Deploy multiple instances of Envoy behind a load balancer to handle increased traffic.
– **Dynamic Configuration**: Use Envoy’s dynamic configuration capabilities to update routes, filters, and clusters without restarting the proxy.
– **Caching**: Implement caching in Envoy to reduce backend load for repeated requests.
– **Observability**: Enhance monitoring with distributed tracing (e.g., Jaeger) and logging (e.g., ELK Stack).

Common Challenges and Solutions

Challenge 1: Performance Overhead

Envoy and Coraza introduce some overhead due to their security and routing capabilities. To mitigate this:

– **Optimize Envoy Configuration**: Use efficient filters and reduce unnecessary processing.
– **Leverage Caching**: Cache responses for static or frequently accessed endpoints.
– **Right-Size Resources**: Allocate appropriate CPU and memory to Envoy instances based on workload.

Challenge 2: Rule Tuning for Coraza WAF

Coraza WAF rules can be overly aggressive, leading to false positives. Solutions include:

– **Start with a Minimal Ruleset**: Begin with a small set of rules (e.g., OWASP Core Rule Set) and gradually add more.
– **Use Exclusion Rules**: Exclude specific paths or IPs from certain rules.
– **Monitor and Adjust**: Continuously review blocked requests and adjust rules based on feedback.

Challenge 3: Service Discovery

Dynamic service discovery can be complex, especially in microservices architectures. Solutions include:

– **Use a Service Mesh**: Tools like Istio or Linkerd can simplify service discovery and load balancing.
– **Leverage Kubernetes**: If using Kubernetes, Envoy can integrate with the service mesh controller for automatic discovery.
– **Static Configurations**: For simpler setups, manually define clusters in Envoy’s configuration.

When to Consider Professional Assistance

Implementing a Gateway API with Envoy and Coraza WAF alongside NGINX requires expertise in:

– **Proxy Configuration**: Fine-tuning Envoy for performance and reliability.
– **Security Policy Design**: Crafting effective Coraza WAF rules without causing false positives.
– **Integration Complexity**: Ensuring seamless interaction between NGINX, Envoy, and backend services.
– **Scalability**: Designing the architecture to handle growth in traffic and complexity.

For organizations facing these challenges, partnering with experts who specialize in platform engineering can provide the necessary guidance to deploy a robust, secure, and scalable Gateway API. X-ITM’s Enterprise Platform offers senior engineering services to help architect, deploy, and optimize such solutions, ensuring alignment with business goals and technical requirements.

Apply this to your environment.

If this problem exists in your estate, we can review the current architecture and determine whether an assessment, pilot or engineering engagement makes sense.

Book a Technical Discovery