# Envoy Gateway Configuration

This document explains how the Envoy unified ingress gateway is configured and how to modify it.

## Files

- deploy/k8s/envoy/envoy.yaml: ConfigMap + Deployment + Service for Envoy

## Current Behavior

- Envoy listens on port 8080 in the Pod and exposes port 80 via a ClusterIP Service.
- Route `/api/users` to `user-api-svc:8888`.
- Route `/api/email` to `email-api-svc:8888`.
- Route `/healthz` returns `200 ok` directly from gateway.
- Unknown routes return `404` from gateway.

## Routing

In envoy.yaml, routes are defined under:

static_resources -> listeners -> http_connection_manager -> route_config -> virtual_hosts

The current routing rules are:

- `prefix: /api/users` -> `cluster: user_api_cluster`
- `prefix: /api/email` -> `cluster: email_api_cluster`
- `path: /healthz` -> direct response `200`
- `prefix: /` -> direct response `404`

To add a new HTTP service, add a new route above the default route and define a new cluster.

Example: route `/api/order` to `order-api-svc:8899`

1) Add a route match:

- match:
    prefix: "/api/order"
  route:
    cluster: order_api_cluster

1) Add a cluster:

- name: order_api_cluster
  connect_timeout: 2s
  type: STRICT_DNS
  lb_policy: ROUND_ROBIN
  load_assignment:
    cluster_name: order_api_cluster
    endpoints:
      - lb_endpoints:
          - endpoint:
              address:
                socket_address:
                  address: order-api-svc.juwan.svc.cluster.local
                  port_value: 8899

## CSRF Protection (Double Cookie)

Envoy uses a Lua filter for double-cookie CSRF validation:

- Safe methods (GET/HEAD/OPTIONS):
  - If missing, Envoy auto-issues two cookies:
    - `csrf_token`
    - `csrf_guard`
- Unsafe methods (POST/PUT/PATCH/DELETE, etc):
  - Requires BOTH headers:
    - `X-CSRF-Token`
    - `X-CSRF-Guard`
  - Requires BOTH cookies:
    - `csrf_token`
    - `csrf_guard`
  - Header values must exactly match cookie values, otherwise Envoy returns `403`.

If you want different cookie or header names, update these constants in Lua:

- `TOKEN_COOKIE`
- `GUARD_COOKIE`
- `TOKEN_HEADER`
- `GUARD_HEADER`

To relax or tighten rules, edit the functions:

- is_safe(method)
- envoy_on_request(request_handle)

## Cookie Attributes

Current Set-Cookie:

- `csrf_token=<value>; Path=/; SameSite=Strict`
- `csrf_guard=<value>; Path=/; SameSite=Strict`

## Deployment

Apply or update:

kubectl apply -f deploy/k8s/envoy/envoy.yaml

## Common Changes

- Change listening port:
  - Update listener port_value and Service targetPort/port.
- Change service namespace:
  - Update cluster DNS addresses (e.g. `service.ns.svc.cluster.local`).
- Add more services:
  - Add route + add cluster, as shown above.
- Update CSRF policy:
  - Edit Lua validation logic in `envoy.filters.http.lua`.
