Skip to content

Add gateway-wide Backend resources and route requests to them by name - #4265

Open
CrowleyRajapakse wants to merge 5 commits into
wso2:mainfrom
CrowleyRajapakse:feature/global-dynamic-endpoints
Open

CrowleyRajapakse wants to merge 5 commits into
wso2:mainfrom
CrowleyRajapakse:feature/global-dynamic-endpoints

Conversation

@CrowleyRajapakse

@CrowleyRajapakse CrowleyRajapakse commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Needs the SDK release before CI can build it. This builds on the SDK PR (#4264), whose commit is the first one here. The policy-engine image compiles against the sdk/core version in its go.mod, so it cannot build until that PR is merged and tagged. I will then add a commit bumping gateway/gateway-runtime/policy-engine/go.mod and mark this ready. The controller, CLI and docs commits do not depend on the SDK change and can be reviewed now.

Split (2026-12-02). This PR was over the 100-file review limit, so two parts moved to their own PRs, each to merge after this one:

This PR is now five commits (SDK, policy engine, controller, CLI, docs) and 92 files, rebased onto current main.

Updated (2026-12-02) after the team's review of the demo:

  • An API's own upstream (upstream.main.ref, upstream.sandbox.ref) can name a Backend.
  • dynamic-endpoint v1.1.0 (dynamic-endpoint v1.1.0: route to gateway-wide Backends by fixed name or CEL expression gateway-controllers#414) has one allowlist, availableBackends, with exact names and name patterns such as orders-*. The label selector is gone; routing never reads a Backend's labels.
  • A templated Backend's placeholder is named by its author ({env}, {tenant}). {key} still works.
  • Every request the gateway can't route gets one 503 with a generic message.
  • Each host a templated Backend's key expands to is checked against the network access control's hostname rules at request time.
  • The new table and config keys follow the repository's migration conventions (gateway/migrations).

Earlier rounds (the rename to Backend, merging targetBackend into targetUpstream, a cluster per Backend revision, templated Backends, and the review fixes) are in the PR timeline. The description below matches the code as pushed.

Purpose

Part of #4269 (phase 1: the gateway side; the control-plane phase follows separately).

An API's backends are declared inside the API (upstream, upstreamDefinitions). Operators who run many interchangeable backends (regional deployments, per-tenant or per-model backends) have to copy them into every API, and adding a backend means editing and redeploying every API that should reach it. The dynamic-endpoint policy can only pick among the API's own upstreamDefinitions.

This PR adds the gateway side of global backends: a gateway-wide Backend resource that any API can route to by name, fixed or chosen per request from the request context, with no API change when Backends are added, changed or removed. The shape of the RestApi schema is unchanged; upstream.main.ref and upstream.sandbox.ref may now name a Backend.

Goals

  • Manage gateway-wide backends as their own resource: kind: Backend, /backends on the management API, and ap gateway apply.
  • Route a request to a Backend: as the API's own upstream, as a fixed target, or chosen at request time (the policy side is dynamic-endpoint v1.1.0, dynamic-endpoint v1.1.0: route to gateway-wide Backends by fixed name or CEL expression gateway-controllers#414).
  • Reach a host chosen per request through a templated Backend (https://api-{env}.example.com).
  • Leave APIs that do not use Backends exactly as they are today: same routes, same clusters.
  • Fail safe: a request the gateway can't route gets a 503, never another backend.

Approach

apiVersion: gateway.choreolabs.com/v1
kind: Backend
metadata:
  name: tenant-b
spec:
  basePath: /v1                # optional; omit it to forward the API-relative path as is
  endpoints:
    - url: http://orders-tenant-b:9080
    - url: http://orders-tenant-1-b:9080
  # tls: { identity, trustedCAs, verifyHostName }, timeout: same keys as an upstreamDefinitions entry

An API reaches it as its own upstream:

spec:
  upstream:
    main:
      ref: tenant-b          # no upstreamDefinitions entry of that name, so it is the Backend

or with dynamic-endpoint v1.1.0:

policies:
  - name: dynamic-endpoint
    version: v1
    params:
      backendExpression: request.Headers["x-tenant"][0]   # or targetUpstream: tenant-b
      availableBackends: [tenant-*]                       # exact names and/or name patterns

Gateway controller

  • POST/GET /backends, GET/PUT/DELETE /backends/{id} (OpenAPI + regenerated server code).

    • The kind is new, so it takes the Choreo Labs API group from the start: apiVersion: gateway.choreolabs.com/v1. Any other apiVersion is a 400.
    • Writes need admin; reads allow admin and developer.
    • Names follow the SDK rule (3–40 characters, lowercase, digits, hyphens) and cannot be changed by an update.
    • metadata.labels are optional and only for organizing Backends; routing does not read them.
  • Validation. spec carries the fields of an upstreamDefinitions entry, with the URLs under endpoints, and is validated by the same rules.

    • Explicit URL ports must be 1–65535, a check now shared with upstream definitions.
    • Errors name the Backend's own fields (spec.endpoints[0].url, spec.basePath, spec.tls.identity).
    • All endpoints of a Backend must use the same scheme.
    • basePath is optional.
  • Storage: a new backends table (SQLite, PostgreSQL, SQL Server) plus an artifacts row of kind Backend, tied together by a foreign key with ON DELETE CASCADE like the other kind tables; an in-memory BackendStore. Updates cannot change the stored name.

  • Migrations, per the repository's designing-db-schemas and changing-gateway-config skills:

    • Schema steps: gateway/migrations/storage/next/{sqlite,postgres,sqlserver}.sql carry the guarded CREATE TABLE backends that brings an existing database forward.
    • Config changelog: gateway/migrations/config/next.yaml declares the two new config keys (added / compatible).
    • // migrate: notes sit on their config.go fields.
  • xDS clusters. Each Backend revision becomes its own cluster, backend_<name>_<revision>, built with the same code path as an upstream definition.

    • The revision is a hash of the Backend's UUID and everything that shapes its cluster or base path (endpoints, weights, base path, TLS, timeouts). Labels and the display name are left out.
    • A tls block gets its own SDS validation-context secret per revision (backend_ca:<name>_<revision>), kept apart from per-API upstream_ca: secrets.
  • Policy engine records. Each Backend is published as a lazy resource of type Backend: {name, clusterName, basePath, labels}, plus urlTemplate and, while access control restricts hostnames, hostRule for a templated Backend.

    • Ordering keeps routing safe. On create or update, the new revision's cluster is pushed, next to the previous revision's, before the record names it. The previous cluster goes only after the record has moved.
    • On delete the record is withdrawn before the cluster.
    • A record and the cluster it names always come from the same revision.
  • Routes. These routes read their cluster from x-target-upstream per request:

    • a route whose policy chain sets a parameter annotated x-choreolabs-backend-routing (name marks a fixed target that may be a Backend, expression a per-request expression);
    • a route whose own upstream names a Backend.

    Every other route keeps today's shape. A route of an API with upstream definitions or a sandbox upstream already reads its cluster that way.

  • An API's own upstream naming a Backend. upstream.main.ref (or upstream.sandbox.ref) that names no entry of the API's upstreamDefinitions refers to the Backend of that name. RestApi only; other kinds keep definitions-only ref.

    • The route builds no cluster of its own. Its route metadata carries default_backend, and the policy engine resolves the Backend per request.
    • The deploy succeeds even if the Backend doesn't exist yet. status.warnings then carries BACKEND_NOT_FOUND (or BACKEND_TEMPLATED for a templated Backend, which needs a key only the policy supplies) for the field, and requests get 503 until the Backend can serve them.
    • Deleting the Backend while a deployed API's upstream names it is refused with 409, naming spec.upstream.main.ref (or the sandbox field).
  • Templated Backends. One endpoint whose first host label holds a placeholder its author names ({env}: a lowercase letter, then up to 31 lowercase letters, digits or underscores), between optional fixed text, with at least one fixed label after it. It has no path, query or user info, and must be the Backend's only endpoint.

    • The template is validated as a URL with a sample key.
    • Its revision becomes an Envoy dynamic forward proxy (DFP) cluster. TLS is set on Cluster.TransportSocket with auto SNI and SAN validation, the same SDS identity and trust secrets, over HTTP/1.1.
    • One DNS cache serves all templated Backends, sized by router.upstream.backend_dns_cache.max_hosts (1024) and host_ttl_ms (300000). Its name carries a hash of its settings.
    • The DFP filter and the route-configuration host_rewrite_header are added only while a templated Backend's cluster exists.
  • TLS. The connection to a Backend always uses the Backend's own tls (identity, trustedCAs, verifyHostName), never the routing API's.

    • Each endpoint gets its own SNI and SAN check. Weights are applied across all endpoints (omitted or 0 counts as 1).
    • Create and update return the same status.warnings an API deploy does (TLS_VERIFY_HOSTNAME_DISABLED, TLS_IDENTITY_EXPIRED), plus a new TLS_NO_TRUST_SOURCE.
  • Guards. Deleting a Backend that a deployed API names as a fixed target is refused with 409: in targetUpstream, or in the API's own upstream.main.ref or upstream.sandbox.ref.

    • The check reads from the database, so a lagging in-memory view can't fool it.
    • An API that has an upstream definition of the same name doesn't block the delete: the definition takes precedence, so the API never uses the Backend.
    • Deleting a certificate that a Backend's tls uses is refused, as for APIs.
    • Names listed in availableBackends don't block a delete. It's an allowlist, not a pin.
  • Network access control (controller.server.network_security.access_control):

    • Endpoints: every Backend endpoint URL is checked like an API upstream URL, on create, update, startup and replica sync. A refused endpoint is a 400 naming the field, never the URL.
    • Templates: checked against their fixed part with a sample key when saved. At request time:
      • the policy engine checks the host each key expands to against the hostname rules (the controller publishes them in the record's hostRule);
      • the DNS cache's resolved_address_filter drops every address the address rules refuse.
  • Replicas: changes are fanned out over the event hub with event type BACKEND, and the immutable-config loader accepts kind: Backend.

    • Each replica serialises reading a Backend and applying it, and removes it from memory by UUID.
    • Records follow the xDS snapshots that were actually applied. A revision whose record the policy engine may hold keeps its cluster until a publish succeeds without it.
  • Requests: POST and PUT /backends read at most 256 KiB and answer 413 beyond it.

  • Control plane: Backends are gateway-local in this phase; the control-plane sync skips them.

Policy engine

  • New directive. A policy can set BackendName (SDK PR).
    • Between UpstreamName and BackendName, the last write in the chain wins.
    • A result that sets both routes to the API's upstream definition of that name when the route has one, and otherwise to the Backend. Creating a Backend therefore never redirects an API away from a definition it declares.
  • A route's own Backend. A route whose own upstream names a Backend (default_backend) resolves it per request through the same path as a policy's fixed target.
    • A policy's choice still wins.
    • Policies see the Backend's current record as the route's default upstream.
  • Fail closed, one answer. The engine answers every Backend it can't route to with 503, engine code 905008, an x-error-id header and the body {"error":"Service Unavailable","message":"The request could not be processed.","error_id":"<id>"}. The log carries the Backend name and the reason:
    • a Backend that doesn't exist;
    • a Backend deleted during the request;
    • a Backend that changed after the policy checked it (revision_changed);
    • a templated Backend without a valid key (key_rejected);
    • a templated Backend whose key expands to a hostname the access control denies (host_refused).
  • Buffered body phase. A header-phase choice of a Backend the gateway lacks, the route's own included, is final only when no buffered body phase follows. A body-phase policy may still choose another target. A streamed request is routed at the header phase and fails at once.
  • Revision pin. A directive may name the revision the policy checked (BackendClusterName). The kernel then routes only while the record names that cluster, so the policy's availableBackends check always holds for the revision the request reaches.
  • Templated Backends.
    • The kernel expands the key and sets x-target-upstream-host. It removes a value the client sent or a policy set for any other target, and Envoy strips the header before forwarding.
    • The expanded host is checked with the same netguard hostname rule the controller uses, compiled once and cached.
    • DNS failure and cache overflow map to 101503 and 303001 for fault handling.
  • Body phase. The engine's own per-request state carries the header phase's choice into the body phase, so a policy can't steer it by writing metadata. A Backend without basePath is sent as /, so the Lua path rewrite keeps the API-relative path.

CLI: ap gateway apply -f accepts kind: Backend.

Kubernetes operator: moved to #4529 (a Backend custom resource synced to /backends).

Test framework and integration scenarios: moved to #4534:

  • the Backend kind in the gateway steps and cleanup;
  • testbench aliases for templated Backends;
  • scenarios GWBE-001–GWBE-010 with their on-prem scenario list.

Known limitation: the controller validates dynamic-endpoint parameters against the policy's JSON schema only, so a backendExpression that does not compile is accepted at deploy. The engine then fails to create the policy, logs the CEL error and answers that route with 500 (905005) until the expression is fixed. executionCondition and advanced-ratelimit CEL expressions behave the same way today. A deploy-time compile check is listed as a follow-up.

Exception requested (ssrf-prevention, directive 2): a fixed, non-templated Backend endpoint's hostname is checked against the network access control's address rules only at certain points: when the Backend is saved, at startup, and on replica sync.

  • Envoy keeps re-resolving it, so a DNS change to a denied address in between isn't caught at dial time.
  • API upstream URLs have exactly this limitation today, documented under "Limitation" in config-template.toml, which now names Backends too.
  • Templated Backends are covered at request time, by the hostname check and the DNS cache's address filter.
  • Envoy's STRICT_DNS clusters have no address filter, and the DFP cluster that has one can't serve weighted multi-endpoint Backends.

Please approve this as an exception per directive 7. A follow-up issue will cover API upstreams and fixed Backends together.

Not in this PR (follow-ups)

  • Pushing Backends from the control plane (platform-api) and the portal UI, designed separately.
  • BackendName in the Python executor bridge.
  • ACK-gated cutover. The syncer treats a change as applied once the controller's xDS caches hold it, not once Envoy and the policy engine have acknowledged it.
    • During a Backend update a request can briefly get 503, but it never reaches another revision's endpoints.
    • API deploys have the same gap; gating on per-client ACKed versions belongs in the shared xDS servers.
  • A deploy-time warning when an API's targetUpstream names neither one of its upstream definitions nor an existing Backend (the API's own upstream.*.ref already warns), and a deploy-time compile check of backendExpression.
  • An ap gateway backend command group (create/list/get/delete); apply works now.
  • Cross-replica atomicity for the reference guards (a certificate delete racing a Backend write, a Backend delete racing an API deploy). They follow the existing API guards.
  • Dial-time address checks for API upstreams and fixed Backends: the exception above.
  • Certificates in immutable mode. An immutable gateway cannot load certificates, so a Backend whose tls names one fails to load. The error names the field and the missing certificate.

User stories

  • As a gateway operator, I add a backend once and every API that allows it can reach it, without redeploying those APIs.
  • As an API developer, I point my API's upstream at a Backend, or route each request to a Backend named by any part of the request (a header, the path or query, metadata set by an earlier policy, or a JWT claim), limited to the names and name patterns I allow.
  • As an API developer, I reach a host chosen per request (api-{env}.example.com) through one templated Backend.
  • As an operator, I cannot delete a Backend that an API is pinned to, or a certificate a Backend trusts.

Documentation

  • docs/gateway/error-codes.md:
    • 905008 and every cause the engine answers with it, including host_refused;
    • the generic body;
    • the shared policy code 960006 that dynamic-endpoint records.
  • docs/gateway/mutual-tls/connect-to-backends-with-mtls.md covers a tls block on a global Backend, how it differs from one on an upstream definition, and its warnings. manage-certificates.md notes that Backends also block a certificate delete.
  • docs/rest-apis/gateway: regenerated with make generate-apidocs. It covers:
    • Backend management;
    • the upstream.ref text;
    • the templated endpoint;
    • the delete rules;
    • TLS_NO_TRUST_SOURCE.
  • gateway/configs/config-template.toml: the DNS cache keys, and how access control applies to templated Backends.
  • The product guide is Document global Backends for the next API Gateway release docs-api-platform#840. The dynamic-endpoint v1.1 policy page is in dynamic-endpoint v1.1.0: route to gateway-wide Backends by fixed name or CEL expression gateway-controllers#414.

Automation tests

  • Unit tests

    SDK: the Backend index and name rule; the cluster a record names; templates with author-named placeholders ({env}, {tenant}; invalid names, two placeholders, braces the wrong way round); the hostRule record key (a malformed rule drops the record); and the 960006 constant.

    Policy engine: the directive (the API's upstream definition first, else the Backend, else fail closed), revision pins, the body-phase deferral, and templated expansion. Also, with a mutation check for each:

    • a route's own Backend: resolved, missing, templated, overridden by a policy, and decided in a buffered body phase;
    • the hostname check for expanded hosts: deny, allow, a rule that doesn't compile, and the 503 body.

    Controller:

    • the validator, including upstream.main.ref names and the template rules;
    • storage, xDS clusters and SDS secrets;
    • the route transform for upstream refs (no static cluster, default_backend, sandbox) and the default_backend route config;
    • publisher and syncer ordering, the publisher's hostRule;
    • the delete guard for upstream.*.ref (mutation-checked) and UpstreamWarnings;
    • the DFP cluster shape, and a test pinning the DNS cache's shipped defaults;
    • the HTTP handlers.

    go test ./... and go vet pass in sdk/core, gateway/gateway-runtime/policy-engine, gateway/gateway-controller and cli/src. One test is flaky on main too: internal/admin TestServer_StartAndStop fails about one run in six on a clean upstream/main checkout, and this PR's only change in that package is one config-dump field.

  • Integration tests

    The scenarios are in Add Backend steps and management scenarios to the test framework #4534. Against gateway images built from this branch and dynamic-endpoint v1.1.0: route to gateway-wide Backends by fixed name or CEL expression gateway-controllers#414 today, on SQLite, PostgreSQL and SQL Server:

    • gateway/migrations/scripts/verify-migrations.sh passes on PostgreSQL. It builds a 1.0.0 database, applies the chain plus next/, and compares the result with a fresh install. check-migration-steps.sh and check-config-changelog.sh pass.
    • An end-to-end walkthrough of every feature (names and patterns, onNoMatch, upstream refs, templated Backends, TLS) passed 58 of 58 checks.

Security checks

  • Followed secure coding standards in http://wso2.com/technical-reports/wso2-secure-engineering-guidelines? yes. The diff was also checked against the repository's .claude/rules:

    • authentication and authorization;
    • error handling;
    • xDS security;
    • SSRF;
    • network hardening;
    • dependencies.

    The SSRF findings were fixed (the per-request hostname check) or raised as the exception above.

  • Ran FindSecurityBugs plugin and verified report? N/A (Go)

  • Confirmed that this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets? yes

Database changes

Not a platform-api change, so the checkbox below does not apply.

The gateway controller schema gains a backends table in all three dialects:

  • SQLite creates it on start, with no schema-version bump.
  • PostgreSQL and SQL Server get the step in gateway/migrations/storage/next/, a guarded CREATE TABLE backends that operators apply before upgrading. A controller that finds the table missing refuses to start.

The release promotes the step into its migration chain.

  • I have applied the same table, column, and index changes to the API Platform SaaS (Bijira Cloud) databases in all relevant environments (dev, staging, production) and regions (US, EU).

Samples

N/A

Related PRs

Merge order:

  1. The SDK PR, then tag sdk/core.
  2. This PR, with the engine go.mod bump.
  3. Manage Backend resources with the Kubernetes gateway operator #4529 and Add Backend steps and management scenarios to the test framework #4534.
  4. A test framework release.
  5. dynamic-endpoint v1.1.0.
  6. The gateway build pins.

Test environment

macOS; Docker (Rancher Desktop) with testcontainers for SQLite, PostgreSQL and SQL Server; Go toolchain per go.mod.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

This review ran on the open-source allowance, not this organization's plan, because the pull request author doesn't have an assigned seat. Waiting won't change this — ask an organization admin to assign them a seat, or add seats in Billing if every seat is already assigned, then retry.

Next included review available in 51 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 39eec7d and 7ca341a.

Files selected for processing: 92

  • cli/src/internal/gateway/resources.go
  • cli/src/utils/constants.go
  • common/eventhub/types.go
  • docs/gateway/error-codes.md
  • docs/gateway/mutual-tls/connect-to-backends-with-mtls.md
  • docs/gateway/mutual-tls/index.md
  • docs/gateway/mutual-tls/manage-certificates.md
  • docs/rest-apis/gateway/README.md
  • docs/rest-apis/gateway/agent-management.md
  • docs/rest-apis/gateway/backend-management.md
  • docs/rest-apis/gateway/graphql-api-management.md
  • docs/rest-apis/gateway/llm-provider-management.md
  • docs/rest-apis/gateway/llm-provider-template-management.md
  • docs/rest-apis/gateway/llm-proxy-management.md
  • docs/rest-apis/gateway/mcp-proxy-management.md
  • docs/rest-apis/gateway/rest-api-management.md
  • docs/rest-apis/gateway/schemas.md
  • gateway/configs/config-template.toml
  • gateway/gateway-controller/api/management-openapi.yaml
  • gateway/gateway-controller/cmd/controller/main.go
  • gateway/gateway-controller/pkg/api/handlers/backend_handler.go
  • gateway/gateway-controller/pkg/api/handlers/backend_handler_test.go
  • gateway/gateway-controller/pkg/api/handlers/certificates.go
  • gateway/gateway-controller/pkg/api/handlers/handlers.go
  • gateway/gateway-controller/pkg/api/handlers/rest_api_handler.go
  • gateway/gateway-controller/pkg/api/management/generated.go
  • gateway/gateway-controller/pkg/backend/backend_test.go
  • gateway/gateway-controller/pkg/backend/publisher.go
  • gateway/gateway-controller/pkg/backend/service.go
  • gateway/gateway-controller/pkg/backend/sync.go
  • gateway/gateway-controller/pkg/config/api_validator.go
  • gateway/gateway-controller/pkg/config/backend_routing.go
  • gateway/gateway-controller/pkg/config/backend_validator.go
  • gateway/gateway-controller/pkg/config/backend_validator_test.go
  • gateway/gateway-controller/pkg/config/config.go
  • gateway/gateway-controller/pkg/config/upstream_tls_validator.go
  • gateway/gateway-controller/pkg/config/validator_test.go
  • gateway/gateway-controller/pkg/constants/constants.go
  • gateway/gateway-controller/pkg/controlplane/sync.go
  • gateway/gateway-controller/pkg/eventlistener/listener.go
  • gateway/gateway-controller/pkg/immutable/loader.go
  • gateway/gateway-controller/pkg/models/backend.go
  • gateway/gateway-controller/pkg/models/backend_template.go
  • gateway/gateway-controller/pkg/models/backend_template_test.go
  • gateway/gateway-controller/pkg/models/backend_test.go
  • gateway/gateway-controller/pkg/models/runtime_deploy_config.go
  • gateway/gateway-controller/pkg/models/stored_config.go
  • gateway/gateway-controller/pkg/policyxds/route_resolution_test.go
  • gateway/gateway-controller/pkg/policyxds/snapshot.go
  • gateway/gateway-controller/pkg/storage/backend_memory.go
  • gateway/gateway-controller/pkg/storage/backend_store.go
  • gateway/gateway-controller/pkg/storage/backend_store_test.go
  • gateway/gateway-controller/pkg/storage/gateway-controller-db.postgres.sql
  • gateway/gateway-controller/pkg/storage/gateway-controller-db.sql
  • gateway/gateway-controller/pkg/storage/gateway-controller-db.sqlserver.sql
  • gateway/gateway-controller/pkg/templateengine/spec.go
  • gateway/gateway-controller/pkg/transform/backend_clusters.go
  • gateway/gateway-controller/pkg/transform/backend_routing_test.go
  • gateway/gateway-controller/pkg/transform/restapi.go
  • gateway/gateway-controller/pkg/upstreamguard/upstreamguard.go
  • gateway/gateway-controller/pkg/upstreamguard/upstreamguard_test.go
  • gateway/gateway-controller/pkg/xds/backend_clusters_test.go
  • gateway/gateway-controller/pkg/xds/backend_dynamic_host.go
  • gateway/gateway-controller/pkg/xds/backend_dynamic_host_test.go
  • gateway/gateway-controller/pkg/xds/sds.go
  • gateway/gateway-controller/pkg/xds/snapshot.go
  • gateway/gateway-controller/pkg/xds/translator.go
  • gateway/gateway-runtime/policy-engine/internal/admin/dumper.go
  • gateway/gateway-runtime/policy-engine/internal/admin/types.go
  • gateway/gateway-runtime/policy-engine/internal/constants/constants.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/backend_host_rule.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/backend_routing_test.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/execution_context.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/extproc.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/fault_engine_fault_test.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/fault_source.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/resolution.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/router_fault_test.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/translator.go
  • gateway/gateway-runtime/policy-engine/internal/kernel/translator_test.go
  • gateway/gateway-runtime/policy-engine/internal/xdsclient/handler.go
  • gateway/migrations/config/next.yaml
  • gateway/migrations/storage/next/postgres.sql
  • gateway/migrations/storage/next/sqlite.sql
  • gateway/migrations/storage/next/sqlserver.sql
  • httpkit/netguard/prefixes.go
  • httpkit/netguard/prefixes_test.go
  • sdk/core/policy/v1alpha2/action.go
  • sdk/core/policy/v1alpha2/backend.go
  • sdk/core/policy/v1alpha2/backend_test.go
  • sdk/core/policy/v1alpha2/fault_codes.go
  • sdk/core/policy/v1alpha2/lazy_resource.go

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

This change adds gateway-wide Backend resources, including management endpoints, persistent storage, validation, and xDS clusters. Policies can route requests to Backends by name or expression. If a selected Backend is unavailable, the policy engine returns a fail-closed 503 response. The Kubernetes operator can also manage Backend resources.

Changes: Gateway-wide Backends

Layer / File(s) Summary
Backend contracts and validation
gateway/gateway-controller/pkg/models/backend.go, gateway/gateway-controller/pkg/config/backend_*, gateway/gateway-controller/pkg/config/api_validator.go, gateway/gateway-controller/pkg/config/backend_routing.go, gateway/gateway-controller/pkg/config/upstream_tls_validator.go, gateway/gateway-controller/pkg/upstreamguard/*, gateway/gateway-controller/pkg/templateengine/spec.go, sdk/core/policy/v1alpha2/backend.go, sdk/core/policy/v1alpha2/action.go, sdk/core/policy/v1alpha2/lazy_resource.go
Adds Backend resource data, validation, policy-routing annotations, SDK lookup from lazy resources, and checks for Backend endpoint URLs.
Storage and synchronization
gateway/gateway-controller/pkg/storage/backend_*, gateway/gateway-controller/pkg/storage/gateway-controller-db.*, gateway/gateway-controller/pkg/backend/*, gateway/gateway-controller/pkg/models/backend.go
Adds Backend storage, CRUD service behavior, lazy-resource publication, and replica synchronization.
Management API and gateway wiring
gateway/gateway-controller/api/management-openapi.yaml, gateway/gateway-controller/pkg/api/..., gateway/gateway-controller/cmd/controller/main.go, gateway/gateway-controller/pkg/immutable/loader.go, gateway/gateway-controller/pkg/eventlistener/listener.go, gateway/gateway-controller/pkg/controlplane/sync.go, gateway/gateway-controller/pkg/models/stored_config.go, cli/src/*, common/eventhub/types.go
Adds Backend management routes and handlers, authorization, artifact loading, event dispatch, CLI endpoints, and certificate-reference checks.
Routing and xDS clusters
gateway/gateway-controller/pkg/transform/*, gateway/gateway-controller/pkg/xds/*, gateway/gateway-controller/pkg/xds/snapshot.go
Enables cluster-header routing for applicable policy chains and adds Backend clusters with endpoint, timeout, weight, and TLS settings.
Policy selection and unavailable-Backend responses
gateway/gateway-runtime/policy-engine/internal/kernel/*, gateway/gateway-runtime/policy-engine/internal/constants/constants.go, sdk/core/policy/v1alpha2/fault_codes.go
Adds Backend routing directives, preserves API-upstream precedence, and returns a 503 when a selected Backend is unavailable.
Kubernetes operator support
kubernetes/gateway-operator/*, kubernetes/helm/operator-helm-chart/*
Adds the Backend custom resource, CRD, RBAC permissions, and controller integration.
Integration coverage and documentation
tests/framework/*, docs/rest-apis/gateway/*, docs/gateway/*
Adds Backend integration scenarios and cleanup support. Documents Backend management, schemas, TLS behavior, certificate references, warning codes, and unavailable-Backend responses.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant PolicyEngine
  participant LazyResourceStore
  participant Envoy
  PolicyEngine->>LazyResourceStore: look up selected Backend
  LazyResourceStore->>PolicyEngine: return cluster name and base path
  PolicyEngine->>Envoy: route request to selected cluster
  LazyResourceStore->>PolicyEngine: indicate missing or changed Backend
  PolicyEngine->>PolicyEngine: return fail-closed 503
Loading
Merge Risk: Moderate · previous review 9f850

Backends can be managed and routed to, with fail-closed 503 handling when a Backend is unavailable. The policy-engine SDK dependency must be released and bumped before this builds, which is a merge-order requirement. The remaining items are minor schema, documentation and test-convention issues plus a few documented, deferred edge cases.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title states the main change: adding gateway-wide Backend resources and routing requests to them by name. The changeset adds the Backend resource (CRD, management API, storage, xDS clusters) and t…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description is detailed and covers Purpose, Goals, Approach, User stories, Documentation, Automation tests, Security checks, Database changes, Samples, Related PRs, and Test environment, so the te…
Full details: Title check

Explanation

The title states the main change: adding gateway-wide Backend resources and routing requests to them by name. The changeset adds the Backend resource (CRD, management API, storage, xDS clusters) and the policy-engine BackendName routing, so the title matches the primary change. It is 69 characters, within a reasonable single-line length.

Full details: Description check

Explanation

The description is detailed and covers Purpose, Goals, Approach, User stories, Documentation, Automation tests, Security checks, Database changes, Samples, Related PRs, and Test environment, so the template structure is fully present. It also records the split, the merge order, the SDK release dependency, and a requested exception under directive 7. The Purpose section links the parent issue (#4269) but does not use the 'Resolves' keyword format. The Security checks section says the diff was checked against repository rules and that the SSRF findings were fixed or raised as an exception, which the author states but does not prove here. The Automation tests section lists unit and integration results, but gives no code coverage figure for this PR; the objectives mention Codecov at 72.36% patch coverage, which the description does not restate. The Database changes checkbox is left unchecked with an explanation that the platform-api check does not apply. The description is long and has some stale pieces, such as the 'Earlier rounds' note, but it matches the code as summarized.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@codecov-commenter

codecov-commenter commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 67.46%. Comparing base (1c07a02) to head (7ca341a).
⚠️ Report is 44 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4265      +/-   ##
==========================================
- Coverage   67.69%   67.46%   -0.24%     
==========================================
  Files        1360     1190     -170     
  Lines      213989   200116   -13873     
  Branches     6808     6734      -74     
==========================================
- Hits       144865   135002    -9863     
+ Misses      59910    56750    -3160     
+ Partials     9214     8364     -850     
Flag Coverage Δ
ai-workspace-bff-unit 82.44% <ø> (ø)
ai-workspace-ui-unit 76.83% <ø> (ø)
api-portal-rest-integration ?
api-portal-unit 76.08% <ø> (+0.75%) ⬆️
unit ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@CrowleyRajapakse
CrowleyRajapakse force-pushed the feature/global-dynamic-endpoints branch 2 times, most recently from 320ac36 to f153726 Compare November 17, 2026 09:46
@CrowleyRajapakse CrowleyRajapakse changed the title Add gateway-wide Endpoint resources and route requests to them by name Add gateway-wide Backend resources and route requests to them by name Nov 17, 2026
@CrowleyRajapakse
CrowleyRajapakse force-pushed the feature/global-dynamic-endpoints branch from f153726 to 09a036e Compare November 18, 2026 07:38
@CrowleyRajapakse
CrowleyRajapakse marked this pull request as ready for review November 18, 2026 08:17
@CrowleyRajapakse
CrowleyRajapakse force-pushed the feature/global-dynamic-endpoints branch from 9f850c5 to eb2ad05 Compare November 26, 2026 08:17
@github-actions

Copy link
Copy Markdown
Contributor

Dependency Validation Results

Dependency name: github.com/cncf/xds/go
Version: v0.0.0-20260202195803-dba9d589def2
Approved: ❌ No - Module not found in dependency registry


Next Steps

  1. Review the validation failures listed above
  2. Check if dependencies are in the approved dependency list
  3. Options to resolve:
    • Remove the unapproved dependencies from this PR
    • OR submit a PR to add these dependencies to the approved list in engineering-governance
  4. Once resolved, push changes to re-run validation

This PR is blocked until all dependencies are approved.

⚠️ Please verify the scope of the dependencies usage is necessary

@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@CrowleyRajapakse
CrowleyRajapakse force-pushed the feature/global-dynamic-endpoints branch 2 times, most recently from edbe5b3 to fde4be4 Compare November 26, 2026 09:49
@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@CrowleyRajapakse
CrowleyRajapakse force-pushed the feature/global-dynamic-endpoints branch 2 times, most recently from 4f93c2a to 143a034 Compare November 26, 2026 10:14
@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Review skipped: 113 files exceed the limit of 100.

@CrowleyRajapakse
CrowleyRajapakse force-pushed the feature/global-dynamic-endpoints branch from 143a034 to 750cce9 Compare November 27, 2026 05:23
@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

CrowleyRajapakse and others added 5 commits December 2, 2026 15:46
- BackendName on UpstreamRequestHeaderModifications and
  UpstreamRequestModifications routes a request to a gateway-wide Backend;
  it shares one last-write-wins slot with UpstreamName. A result that sets
  both routes to the API's upstream definition named UpstreamName when the
  API has one, and otherwise to the Backend named BackendName.
- LookupBackend resolves a Backend from the lazy resource store, with a
  parsed index cached per store version; BackendInfo.MatchesLabels applies
  a matchLabels selector; IsValidBackendName checks the name rule.
- BackendInfo.ClusterName is the cluster the record names, accepted only
  when it is one of that Backend's own clusters (backend_<name>, or
  backend_<name>_<hex revision>); a record naming any other cluster is
  ignored. The gateway serves each revision of a Backend from its own
  cluster, so a record and its cluster always come from the same revision.
- Fault code 905008 (FaultCodeBackendUnavailable) for a request routed to
  a Backend the gateway does not hold.
- Templated Backends: BackendURLTemplate (ParseBackendURLTemplate, Expand)
  for an endpoint whose first host label holds one placeholder its author
  names, such as {env}; the published urlTemplate record key; BackendKey on
  both modification types fills it per request; IsValidBackendKey keeps
  a key to one DNS label.
- BackendInfo.HostRule (record key hostRule): the network access control's
  hostname rule a templated Backend's expanded host must pass. A record
  whose rule can't be read is dropped, so its Backend is never reached.
- FaultCodeNoBackendAvailable (960006), a shared policy code for a
  backend-routing policy with no Backend it may route a request to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The upstream redirect directive accepts a Backend as well as an
  upstream definition, last write wins across the chain. A directive that
  names both resolves to the API's upstream definition of that name when
  the route has one, else to the Backend, so creating a Backend never
  redirects an API away from a definition it declares.
- A Backend resolves to its backend_<name> cluster and base path through
  the existing x-target-upstream and Lua rewrite; an empty base path is sent
  as "/" so the API's own base path is not applied.
- A missing Backend fails closed with 503, engine code 905008 and an
  x-error-id, instead of falling back to the route's default upstream.
- The body phase restores the header-phase choice from a "backend:" label.
  A header-phase choice of a missing Backend waits for a buffered body
  phase, whose policies may still choose another target; a streamed
  request fails at once. The 905008 reply keeps the request's analytics.
- Document 905008 in the gateway error codes.
- Templated Backends: the key fills the template, the expanded host goes
  to the dynamic forward proxy in x-target-upstream-host (a client-sent
  value is always removed), and the host must pass the access control's
  hostname rule. A missing or invalid key, or a refused host, fails closed
  with the same 503.
- Every 905008 reply carries the generic message "The request could not
  be processed." beside its error_id.
- A route whose own upstream names a Backend (route metadata
  default_backend) resolves it per request through the same path as a
  policy's fixed target; a policy's choice still wins, and a missing
  Backend fails closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- kind: Backend at /api/management/v1/backends (admins write, developers
  read), with apiVersion gateway.choreolabs.com/v1, the Choreo Labs API
  group new kinds use (existing kinds keep theirs), validated with the upstreamDefinitions rules and a lowercase,
  3-40 character name rule. Its URLs are listed under spec.endpoints, and
  errors name the Backend's own fields (spec.endpoints[i].url,
  spec.basePath, spec.tls).
- Stored in a new backends table plus an artifacts row in all three
  dialects, tied by a cascading foreign key; loaded before the first
  snapshot; synced across replicas with a new BACKEND event. Each replica
  serialises reading and applying a Backend, removes it from memory by
  UUID, publishes a record only for a revision whose cluster is in the
  last applied snapshot (and only if the translator built it), keeps every
  revision a record may still name in later snapshots until a publish
  succeeds without it, and re-pushes the records after a failed push.
- Endpoint URLs pass controller.server.network_security.access_control
  like API upstream URLs: a refused one is a 400 naming the field, and a
  stored Backend refused after a restart or on another replica is not
  served.
- One cluster per Backend revision, backend_<name>_<revision> (a hash of
  the UUID, endpoints, weights, base path, TLS and timeouts), built by the
  converter upstreamDefinitions now share, with a backend_ca: SDS secret
  per revision for its trusted CAs. A record {name, clusterName, basePath,
  labels} names its revision's cluster: it is published after that
  cluster, and on an update the previous cluster stays until the record
  has moved, so a request never pairs one revision's base path with
  another's endpoints; on delete the record is withdrawn first.
- A route becomes divertible when its policy chain sets a parameter
  annotated x-choreolabs-backend-routing (name for a fixed target, which
  is the API's own upstream definition of that name if it has one and a
  Backend otherwise; expression for a per-request expression); every other
  route keeps its shape.
- Deleting a Backend a deployed API names as a fixed target is refused
  with 409, unless that API has an upstream definition of the same name,
  which takes precedence; certificate deletes are refused while a Backend's tls block
  names the certificate.
- POST and PUT /backends return tls warnings in status.warnings and log
  them: TLS_VERIFY_HOSTNAME_DISABLED, TLS_IDENTITY_EXPIRED, and the new
  TLS_NO_TRUST_SOURCE (https endpoints, no trustedCAs, empty gateway trust
  bundle; a warning, not a 400, because the bundle can change later).
- POST and PUT /backends read at most 256 KiB (413 beyond it).
- Backend artifacts load first in immutable mode, and stay out of the
  control-plane push until the control plane can import them.
- Templated Backends: one endpoint whose first host label holds a
  placeholder its author names ({env}); served by a dynamic forward proxy
  cluster per revision with a shared DNS cache
  (router.upstream.backend_dns_cache.max_hosts / host_ttl_ms, declared in
  gateway/migrations/config/next.yaml) whose resolved_address_filter
  applies the access control's address rules. The record publishes the
  template and, while access control restricts hostnames, its hostname
  rule for the policy engine to check each expanded host.
- upstream.main.ref and upstream.sandbox.ref of a RestApi may name a
  Backend when the API has no upstreamDefinitions entry of that name: the
  route builds no cluster of its own, the policy engine resolves the
  Backend per request, the deploy warns BACKEND_NOT_FOUND or
  BACKEND_TEMPLATED, and deleting the Backend is refused with 409.
- gateway/migrations/storage/next: guarded CREATE TABLE steps for the
  backends table in all three dialects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- connect-to-backends-with-mtls.md: a tls block on a global Backend, how
  it differs from one on an upstream definition, and its warnings.
- manage-certificates.md: Backends also block a certificate delete.
- docs/rest-apis/gateway: regenerated with make generate-apidocs, adding
  Backend management and TLS_NO_TRUST_SOURCE.
- error-codes.md: the 905008 causes, including templated Backends and an
  API's own upstream naming a Backend, and the shared policy code 960006.
- docs/rest-apis/gateway: regenerated for templated Backends, upstream
  refs naming a Backend, and the Backend delete rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CrowleyRajapakse

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Review rate limited.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 51 minutes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants