# Path Rewriting
#
# Rewrite request paths before forwarding to upstream.
#
# Rewrite pipeline (per request):
#
#   Incoming path
#        |
#        v
#   +---------------------+
#   | strip_prefix        |  /api/v1/users -> /users
#   +---------------------+
#        |
#        v
#   +---------------------+
#   | add_prefix          |  (if set) /users -> /svc/users
#   +---------------------+
#        |
#        v
#   +---------------------+
#   | replace (regex)     |  /old/resource -> /new/resource
#   +---------------------+
#        |
#        v
#   Rewritten path (used by router)
#
# Usage:
#   cargo run -p praxis-proxy -- -c examples/configs/transformation/path-rewriting.yaml
#   curl http://localhost:8080/api/v1/users
#     -> upstream sees /users
#   curl http://localhost:8080/old/resource
#     -> upstream sees /new/resource
#   curl http://localhost:8080/items
#     -> upstream sees /svc/items
#
# The first filter strips the /api/v1 prefix, the second
# rewrites /old/... to /new/... via regex, and the third
# prepends /svc to /items paths.
#
# NOTE: The router checks rewritten_path before the original
# URI, so "rewrite then route" pipelines work: place a rewrite
# filter before the router and the router will match against
# the rewritten path.
#
# If both path_rewrite and url_rewrite (or two path_rewrite
# filters) appear in the same pipeline, only the last one's
# rewrite takes effect. Validation rejects this by default.
# The three path_rewrite entries below are safe because their
# conditions are mutually exclusive (only one fires per
# request).

listeners:
  - name: default
    address: "127.0.0.1:8080"
    filter_chains:
      - main

filter_chains:
  - name: main
    filters:
      - filter: router
        routes:
          - path_prefix: "/"
            cluster: backend

      - filter: path_rewrite
        strip_prefix: "/api/v1"
        conditions:
          - when:
              path_prefix: "/api/v1"

      - filter: path_rewrite
        replace:
          pattern: "^/old/(.*)"
          replacement: "/new/$1"
        # Permits a later rewrite filter to override an earlier one.
        # Security consideration: filter order matters; the last
        # rewrite wins, so misordering can bypass path-based ACLs.
        allow_rewrite_override: true
        conditions:
          - when:
              path_prefix: "/old/"

      - filter: path_rewrite
        add_prefix: "/svc"
        allow_rewrite_override: true
        conditions:
          - when:
              path_prefix: "/items"

      - filter: load_balancer
        clusters:
          - name: backend
            endpoints:
              - "127.0.0.1:3000"

insecure_options:
  allow_private_endpoints: true # example proxies to local backends
