Repository navigation
Add gateway-wide Backend resources and route requests to them by name - #4265
CrowleyRajapakse wants to merge 5 commits into
Conversation
|
Warning Review limit reachedThis 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. View limit details
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Merge Risk:
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
320ac36 to
f153726
Compare
f153726 to
09a036e
Compare
9f850c5 to
eb2ad05
Compare
Dependency Validation ResultsDependency name: github.com/cncf/xds/go Next Steps
|
|
@coderabbitai review |
Action not completed
|
edbe5b3 to
fde4be4
Compare
|
@coderabbitai review |
Action not completed
|
4f93c2a to
143a034
Compare
|
@coderabbitai review |
Action not completed
|
|
@coderabbitai review |
Action not completed
|
|
@coderabbitai full review |
Action not completed
|
143a034 to
750cce9
Compare
|
@coderabbitai review |
Action not completed
|
- 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>
750cce9 to
7ca341a
Compare
|
@coderabbitai full review |
Action not completed
|
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. Thedynamic-endpointpolicy can only pick among the API's ownupstreamDefinitions.This PR adds the gateway side of global backends: a gateway-wide
Backendresource 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 theRestApischema is unchanged;upstream.main.refandupstream.sandbox.refmay now name a Backend.Goals
kind: Backend,/backendson the management API, andap gateway apply.dynamic-endpointv1.1.0, dynamic-endpoint v1.1.0: route to gateway-wide Backends by fixed name or CEL expression gateway-controllers#414).https://api-{env}.example.com).503, never another backend.Approach
An API reaches it as its own upstream:
or with
dynamic-endpointv1.1.0:Gateway controller
POST/GET /backends,GET/PUT/DELETE /backends/{id}(OpenAPI + regenerated server code).apiVersion: gateway.choreolabs.com/v1. Any other apiVersion is a 400.admin; reads allowadminanddeveloper.metadata.labelsare optional and only for organizing Backends; routing does not read them.Validation.
speccarries the fields of anupstreamDefinitionsentry, with the URLs underendpoints, and is validated by the same rules.spec.endpoints[0].url,spec.basePath,spec.tls.identity).basePathis optional.Storage: a new
backendstable (SQLite, PostgreSQL, SQL Server) plus anartifactsrow of kindBackend, tied together by a foreign key withON DELETE CASCADElike the other kind tables; an in-memoryBackendStore. Updates cannot change the stored name.Migrations, per the repository's
designing-db-schemasandchanging-gateway-configskills:gateway/migrations/storage/next/{sqlite,postgres,sqlserver}.sqlcarry the guardedCREATE TABLE backendsthat brings an existing database forward.gateway/migrations/config/next.yamldeclares the two new config keys (added/compatible).// migrate:notes sit on theirconfig.gofields.xDS clusters. Each Backend revision becomes its own cluster,
backend_<name>_<revision>, built with the same code path as an upstream definition.tlsblock gets its own SDS validation-context secret per revision (backend_ca:<name>_<revision>), kept apart from per-APIupstream_ca:secrets.Policy engine records. Each Backend is published as a lazy resource of type
Backend:{name, clusterName, basePath, labels}, plusurlTemplateand, while access control restricts hostnames,hostRulefor a templated Backend.Routes. These routes read their cluster from
x-target-upstreamper request:x-choreolabs-backend-routing(namemarks a fixed target that may be a Backend,expressiona per-request expression);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(orupstream.sandbox.ref) that names no entry of the API'supstreamDefinitionsrefers to the Backend of that name. RestApi only; other kinds keep definitions-onlyref.default_backend, and the policy engine resolves the Backend per request.status.warningsthen carriesBACKEND_NOT_FOUND(orBACKEND_TEMPLATEDfor a templated Backend, which needs a key only the policy supplies) for the field, and requests get503until the Backend can serve them.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.Cluster.TransportSocketwith auto SNI and SAN validation, the same SDS identity and trust secrets, over HTTP/1.1.router.upstream.backend_dns_cache.max_hosts(1024) andhost_ttl_ms(300000). Its name carries a hash of its settings.host_rewrite_headerare 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.status.warningsan API deploy does (TLS_VERIFY_HOSTNAME_DISABLED,TLS_IDENTITY_EXPIRED), plus a newTLS_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 ownupstream.main.reforupstream.sandbox.ref.tlsuses is refused, as for APIs.availableBackendsdon't block a delete. It's an allowlist, not a pin.Network access control (
controller.server.network_security.access_control):hostRule);resolved_address_filterdrops every address the address rules refuse.Replicas: changes are fanned out over the event hub with event type
BACKEND, and the immutable-config loader acceptskind: Backend.Requests:
POSTandPUT /backendsread 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
BackendName(SDK PR).UpstreamNameandBackendName, the last write in the chain wins.default_backend) resolves it per request through the same path as a policy's fixed target.x-error-idheader 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:revision_changed);key_rejected);host_refused).BackendClusterName). The kernel then routes only while the record names that cluster, so the policy'savailableBackendscheck always holds for the revision the request reaches.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.netguardhostname rule the controller uses, compiled once and cached.101503and303001for fault handling.basePathis sent as/, so the Lua path rewrite keeps the API-relative path.CLI:
ap gateway apply -facceptskind: Backend.Kubernetes operator: moved to #4529 (a
Backendcustom resource synced to/backends).Test framework and integration scenarios: moved to #4534:
Backendkind in the gateway steps and cleanup;GWBE-001–GWBE-010with their on-prem scenario list.Known limitation: the controller validates
dynamic-endpointparameters against the policy's JSON schema only, so abackendExpressionthat 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.executionConditionandadvanced-ratelimitCEL 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.
config-template.toml, which now names Backends too.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)
BackendNamein the Python executor bridge.503, but it never reaches another revision's endpoints.targetUpstreamnames neither one of its upstream definitions nor an existing Backend (the API's ownupstream.*.refalready warns), and a deploy-time compile check ofbackendExpression.ap gateway backendcommand group (create/list/get/delete);applyworks now.tlsnames one fails to load. The error names the field and the missing certificate.User stories
api-{env}.example.com) through one templated Backend.Documentation
docs/gateway/error-codes.md:host_refused;dynamic-endpointrecords.docs/gateway/mutual-tls/connect-to-backends-with-mtls.mdcovers atlsblock on a global Backend, how it differs from one on an upstream definition, and its warnings.manage-certificates.mdnotes that Backends also block a certificate delete.docs/rest-apis/gateway: regenerated withmake generate-apidocs. It covers:upstream.reftext;TLS_NO_TRUST_SOURCE.gateway/configs/config-template.toml: the DNS cache keys, and how access control applies to templated Backends.dynamic-endpointv1.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
gateway/migrations/scripts/verify-migrations.shpasses on PostgreSQL. It builds a 1.0.0 database, applies the chain plusnext/, and compares the result with a fresh install.check-migration-steps.shandcheck-config-changelog.shpass.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: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
backendstable in all three dialects:gateway/migrations/storage/next/, a guardedCREATE TABLE backendsthat operators apply before upgrading. A controller that finds the table missing refuses to start.The release promotes the step into its migration chain.
Samples
N/A
Related PRs
GWBEintegration scenarios in the test framework (merge after this PR)dynamic-endpointv1.1.0Merge order:
sdk/core.go.modbump.dynamic-endpointv1.1.0.Test environment
macOS; Docker (Rancher Desktop) with testcontainers for SQLite, PostgreSQL and SQL Server; Go toolchain per
go.mod.🤖 Generated with Claude Code