← Back to Pull requests

feat: add TrafficPolicy requestMirror policy #14441

Merged
JCigan merged 14 files (1576 lines) on Aug 17, 2026 17:24 UTC
View on GitHub
JCigan JCigan commented on Jul 20, 2026 21:46 UTC
Author

Description

Implements options to control the Host/:authority header of mirrored requests to upstream shadow hosts. Gateway API, which this gateway relies on, can't properly express Envoy's disable_shadow_host_suffix_append or host_rewrite_literal mirror options. This PR adds a requestMirror field to TrafficPolicy exposing those Envoy fields. disableShadowHostSuffixAppend disables the automatically appended -shadow suffix on that header value, and hostRewriteLiteral replaces the mirrored header value with a literal value.

Added unit and translator tests. In the future, it would be good to add a data plane e2e test case asserting that a mirrored request's Host is correctly configured without -shadow appended when the options added in this PR are enabled. Attempted to add such a test for this PR, but encountered difficulties around asserting what Host/:authority header the mirror received.

Change Type

/kind feature

Changelog

``release-note
Added
spec.requestMirror to TrafficPolicy. This field allows users to control the Host/:authority header of mirrored requests. disableShadowHostSuffixAppend disables appending -shadow to the end of the Host/:authority header value, and hostRewriteLiteral replaces the mirrored Host/:authority header value with a literal value.
`

Additional Notes

The implementation augments existing mirrors rather than defining new ones, so the filter still owns the destination, percentage, and existence of the mirror. Here, TrafficPolicy only tweaks some Envoy-specific behavior for mirrors already on the route, which avoids needing a second way to declare mirrors for this feature.

When attached at multiple scopes, the whole requestMirror block from the most-specific policy wins. So Route > Listener > Gateway is the order of precedence.

Applies to mirrors from both HTTPRoute and GRPCRoute` filters.

Diff: 1576 lines (+1569 / -7) across 14 files Reviewer: ymesika Review duration: 40058m
All Vouch review confidence checks passed
Residual risk 0.16 = Change Risk (0.62) × (1 − Review Confidence (0.75)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.62 · 1576 lines diff across 14 files
0.62
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.51 · 5 substantive comment(s)
0.51
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
74%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
31 items
Copilot Copilot commented on code on Jul 20, 2026 21:51 UTC
Code Review
test/e2e/features/requestmirror/suite.go:1
@@ -0,0 +1,91 @@
+//go:build e2e
+
+package requestmirror
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/suite"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	gwv1 "sigs.k8s.io/gateway-api/apis/v1"
+
+	"github.com/kgateway-dev/kgateway/v2/pkg/utils/requestutils/curl"
+	"github.com/kgateway-dev/kgateway/v2/test/e2e"
+	"github.com/kgateway-dev/kgateway/v2/test/e2e/common"
+	"github.com/kgateway-dev/kgateway/v2/test/e2e/defaults"
+	"github.com/kgateway-dev/kgateway/v2/test/e2e/tests/base"
+	"github.com/kgateway-dev/kgateway/v2/test/gomega/matchers"
+)
+
+var _ e2e.NewSuiteFunc = NewTestingSuite
+
+type testingSuite struct {
+	*base.BaseTestingSuite
+}
+
+func NewTestingSuite(ctx context.Context, testInst *e2e.TestInstallation) suite.TestingSuite {
+	return &testingSuite{
+		base.NewBaseTestingSuite(ctx, testInst, setup, nil),
+	}
+}
+
+func (s *testingSuite) SetupSuite() {
+	s.BaseTestingSuite.SetupSuite()
+
+	// Wait for the sink access-log policy and the mirror routes to be programmed before sending.
+	s.TestInstallation.AssertionsT(s.T()).EventuallyHTTPListenerPolicyCondition(
+		s.Ctx, "mirror-sink-logs", "kgateway-base", gwv1.GatewayConditionAccepted, metav1.ConditionTrue)
+	s.TestInstallation.AssertionsT(s.T()).EventuallyHTTPRouteCondition(
+		s.Ctx, "mirror-keep-host", "kgateway-base", gwv1.RouteConditionAccepted, metav1.ConditionTrue)
+	s.TestInstallation.AssertionsT(s.T()).EventuallyHTTPRouteCondition(
+		s.Ctx, "mirror-default-host", "kgateway-base", gwv1.RouteConditionAccepted, metav1.ConditionTrue)
+}
+
+// TestMirrorPreservesHostWhenDisabled verifies that with disableShadowHostSuffixAppend=true the
+// mirror receives the original :authority, with no "-shadow" suffix.
+func (s *testingSuite) TestMirrorPreservesHostWhenDisabled() {
+	s.assertMirroredAuthority("/anything/keep-host", `"authority":"mirror.example.com"`)
+}
+
+// TestMirrorAppendsShadowByDefault verifies the default (no policy) still appends "-shadow".
+func (s *testingSuite) TestMirrorAppendsShadowByDefault() {
+	s.assertMirroredAuthority("/anything/default-host", `"authority":"mirror.example.com-shadow"`)
+}
+
+// assertMirroredAuthority sends a request to path and asserts the mirror-sink log records
+// wantAuthority. Mirroring is fire-and-forget, so the request is re-sent each poll until the log
+// records it.
+func (s *testingSuite) assertMirroredAuthority(path, wantAuthority string) {
+	pods := s.mirrorSinkPods()
+
+	s.Require().EventuallyWithT(func(c *assert.CollectT) {
+		common.BaseGateway.Send(
+			s.T(),
+			&matchers.HttpResponse{StatusCode: http.StatusOK},
+			curl.WithHostHeader("mirror.example.com"),
+			curl.WithPath(path),
+			curl.WithPort(80),
+		)
+
+		logs, err := s.TestInstallation.Actions.Kubectl().GetContainerLogs(
+			s.Ctx, mirrorSinkObjectMeta.GetNamespace(), pods[0])
+		assert.NoError(c, err)
+		assert.Contains(c, logs, fmt.Sprintf(`"path":"%s"`, path))
+		assert.Contains(c, logs, wantAuthority)
+	}, 30*time.Second, 1*time.Second)

The e2e assertion can produce false positives because it checks for the expected path and expected authority as two independent substrings; those could be present in different access-log entries. It also only reads logs from pods[0], which can miss the mirrored request if multiple proxy pods exist. Consider aggregating logs from all matching pods and asserting on a single log record substring that contains both the expected authority and the expected path.

copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Jul 20, 2026 21:51 UTC
Reviewer

Pull request overview

This PR extends the TrafficPolicy API to expose Envoy’s disable_shadow_host_suffix_append behavior for request mirroring, allowing users to preserve the original Host/:authority header (no -shadow suffix) when mirroring traffic. It fits into kgateway’s policy->IR->xDS pipeline by adding a small TrafficPolicy sub-IR that mutates existing Envoy requestMirrorPolicies generated from HTTPRoute/GRPCRoute RequestMirror filters.

Changes:

  • Add spec.requestMirror.disableShadowHostSuffixAppend to the TrafficPolicy CRD/API types (with schema validation) and generated deepcopy.

  • Translate/merge/apply the new TrafficPolicy request-mirror sub-IR into Envoy route mirror policies, including unit tests and translator golden coverage.

  • Add an end-to-end suite (and CI wiring) to validate data-plane behavior for mirrored :authority with/without the -shadow suffix.
  • Reviewed changes

    Copilot reviewed 17 out of 18 changed files in this pull request and generated 1 comment.

    <details>
    <summary>Show a summary per file</summary>

    | File | Description |
    | ---- | ----------- |
    | test/e2e/tests/kgateway/suite_runner.go | Registers the new RequestMirror e2e suite. |
    | test/e2e/tests/apivalidation/apivalidation.go | Adds CRD validation coverage for rejecting empty requestMirror: {}. |
    | test/e2e/features/requestmirror/types.go | Defines suite setup manifest wiring for the new request mirror feature test. |
    | test/e2e/features/requestmirror/testdata/setup.yaml | Adds gateway/routes/policies to exercise mirrored :authority behavior. |
    | test/e2e/features/requestmirror/suite.go | Implements the RequestMirror e2e assertions for -shadow suffix behavior. |
    | pkg/kgateway/translator/gateway/testutils/outputs/traffic-policy/request-mirror.yaml | Adds/updates golden output verifying Envoy disableShadowHostSuffixAppend rendering. |
    | pkg/kgateway/translator/gateway/testutils/inputs/traffic-policy/request-mirror.yaml | Adds translator input coverage for gateway/route TrafficPolicy request mirror behavior. |
    | pkg/kgateway/translator/gateway/gateway_translator_test.go | Runs the new translator golden test case. |
    | pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go | Applies request-mirror settings per-route and tracks precedence across attachment levels. |
    | pkg/kgateway/extensions2/plugins/trafficpolicy/request_mirror.go | Introduces request-mirror sub-IR, construction, equality, and Envoy mutation logic. |
    | pkg/kgateway/extensions2/plugins/trafficpolicy/request_mirror_test.go | Unit tests for IR construction, equality, and application behavior. |
    | pkg/kgateway/extensions2/plugins/trafficpolicy/merge.go | Adds merge support for request-mirror sub-IR. |
    | pkg/kgateway/extensions2/plugins/trafficpolicy/merge_test.go | Adds merge tests for request-mirror precedence/behavior. |
    | pkg/kgateway/extensions2/plugins/trafficpolicy/constructor.go | Wires request-mirror IR construction into TrafficPolicy IR building. |
    | install/helm/kgateway-crds/templates/gateway.kgateway.dev_trafficpolicies.yaml | Updates CRD schema docs/validation for the new requestMirror block. |
    | api/v1alpha1/kgateway/zz_generated.deepcopy.go | Adds deepcopy support for the new API types/fields. |
    | api/v1alpha1/kgateway/traffic_policy_types.go | Adds RequestMirror to TrafficPolicySpec and defines RequestMirrorPolicy. |
    | .github/workflows/e2e.yaml | Includes the RequestMirror suite in CI execution regex. |
    </details>

    <details>
    <summary>Files not reviewed (1)</summary>

  • api/v1alpha1/kgateway/zz_generated.deepcopy.go: Generated file

  • </details>

    JCigan JCigan commented on code on Jul 20, 2026 22:07 UTC
    Code Review
    test/e2e/features/requestmirror/suite.go:1
    @@ -0,0 +1,91 @@
    +//go:build e2e
    +
    +package requestmirror
    +
    +import (
    +	"context"
    +	"fmt"
    +	"net/http"
    +	"time"
    +
    +	"github.com/stretchr/testify/assert"
    +	"github.com/stretchr/testify/suite"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	gwv1 "sigs.k8s.io/gateway-api/apis/v1"
    +
    +	"github.com/kgateway-dev/kgateway/v2/pkg/utils/requestutils/curl"
    +	"github.com/kgateway-dev/kgateway/v2/test/e2e"
    +	"github.com/kgateway-dev/kgateway/v2/test/e2e/common"
    +	"github.com/kgateway-dev/kgateway/v2/test/e2e/defaults"
    +	"github.com/kgateway-dev/kgateway/v2/test/e2e/tests/base"
    +	"github.com/kgateway-dev/kgateway/v2/test/gomega/matchers"
    +)
    +
    +var _ e2e.NewSuiteFunc = NewTestingSuite
    +
    +type testingSuite struct {
    +	*base.BaseTestingSuite
    +}
    +
    +func NewTestingSuite(ctx context.Context, testInst *e2e.TestInstallation) suite.TestingSuite {
    +	return &testingSuite{
    +		base.NewBaseTestingSuite(ctx, testInst, setup, nil),
    +	}
    +}
    +
    +func (s *testingSuite) SetupSuite() {
    +	s.BaseTestingSuite.SetupSuite()
    +
    +	// Wait for the sink access-log policy and the mirror routes to be programmed before sending.
    +	s.TestInstallation.AssertionsT(s.T()).EventuallyHTTPListenerPolicyCondition(
    +		s.Ctx, "mirror-sink-logs", "kgateway-base", gwv1.GatewayConditionAccepted, metav1.ConditionTrue)
    +	s.TestInstallation.AssertionsT(s.T()).EventuallyHTTPRouteCondition(
    +		s.Ctx, "mirror-keep-host", "kgateway-base", gwv1.RouteConditionAccepted, metav1.ConditionTrue)
    +	s.TestInstallation.AssertionsT(s.T()).EventuallyHTTPRouteCondition(
    +		s.Ctx, "mirror-default-host", "kgateway-base", gwv1.RouteConditionAccepted, metav1.ConditionTrue)
    +}
    +
    +// TestMirrorPreservesHostWhenDisabled verifies that with disableShadowHostSuffixAppend=true the
    +// mirror receives the original :authority, with no "-shadow" suffix.
    +func (s *testingSuite) TestMirrorPreservesHostWhenDisabled() {
    +	s.assertMirroredAuthority("/anything/keep-host", `"authority":"mirror.example.com"`)
    +}
    +
    +// TestMirrorAppendsShadowByDefault verifies the default (no policy) still appends "-shadow".
    +func (s *testingSuite) TestMirrorAppendsShadowByDefault() {
    +	s.assertMirroredAuthority("/anything/default-host", `"authority":"mirror.example.com-shadow"`)
    +}
    +
    +// assertMirroredAuthority sends a request to path and asserts the mirror-sink log records
    +// wantAuthority. Mirroring is fire-and-forget, so the request is re-sent each poll until the log
    +// records it.
    +func (s *testingSuite) assertMirroredAuthority(path, wantAuthority string) {
    +	pods := s.mirrorSinkPods()
    +
    +	s.Require().EventuallyWithT(func(c *assert.CollectT) {
    +		common.BaseGateway.Send(
    +			s.T(),
    +			&matchers.HttpResponse{StatusCode: http.StatusOK},
    +			curl.WithHostHeader("mirror.example.com"),
    +			curl.WithPath(path),
    +			curl.WithPort(80),
    +		)
    +
    +		logs, err := s.TestInstallation.Actions.Kubectl().GetContainerLogs(
    +			s.Ctx, mirrorSinkObjectMeta.GetNamespace(), pods[0])
    +		assert.NoError(c, err)
    +		assert.Contains(c, logs, fmt.Sprintf(`"path":"%s"`, path))
    +		assert.Contains(c, logs, wantAuthority)
    +	}, 30*time.Second, 1*time.Second)

    Addressed in third commit

    ymesika ymesika commented on code on Jul 21, 2026 07:29 UTC
    Code Review
    api/v1alpha1/kgateway/traffic_policy_types.go:1
    @@ -225,6 +231,18 @@ type TrafficPolicySpec struct {
     	StatPrefix *string `json:"statPrefix,omitempty"`
     }
     
    +// RequestMirrorPolicy configures implementation-specific behavior for request mirrors.
    +// +kubebuilder:validation:MinProperties=1
    +type RequestMirrorPolicy struct {
    +	// DisableShadowHostSuffixAppend controls whether Envoy appends the "-shadow"
    +	// suffix to the Host or :authority header of mirrored requests.
    +	// When true, the original Host or :authority header is preserved.
    +	// When false, Envoy appends the suffix. When unset, the existing mirror

    nit: mention that it's also when unset (default)

    ymesika ymesika commented on code on Jul 21, 2026 07:32 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    nit: A bit unique pattern to have pointers set here. A one-line comment noting it's scoped to a single translation pass (pointers unique per pass, so no cross-route/cross-gateway collision) would help future readers.

    ymesika ymesika commented on Jul 21, 2026 07:34 UTC
    Reviewer

    LG overall but this PR is about GRPCRoute support but every translator/golden case is HTTPRoute. Worth adding one GRPCRoute rule to request-mirror.yaml (i think) to actually exercise this.

    JCigan JCigan commented on code on Jul 21, 2026 13:01 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    Yeah, that's worth calling out - will add a comment to that effect. Also working on adding the GRPCRoute golden case that you asked for

    davidjumani davidjumani commented on code on Jul 21, 2026 13:48 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    This struct is needed if this section of the policy requires an empty filter in the chain to overwrite at the route level. If this does not rely on the filter chain, can it be added only to the trafficPolicySpecIr like AutoHostRewrite ?

    davidjumani davidjumani commented on code on Jul 21, 2026 13:53 UTC
    Code Review
    api/v1alpha1/kgateway/traffic_policy_types.go:1
    @@ -90,6 +90,12 @@ type TrafficPolicySpec struct {
     	// +optional
     	HeaderModifiers *shared.HeaderModifiers `json:"headerModifiers,omitempty"`
     
    +	// RequestMirror configures the behavior of request mirrors defined by
    +	// HTTPRoute or GRPCRoute RequestMirror filters. It does not create request mirrors.
    +	// If a targeted route has no request mirrors, this configuration has no effect.
    +	// +optional
    +	RequestMirror *RequestMirrorPolicy `json:"requestMirror,omitempty"`

    Should this apply only to roues or gateways as well ?

    davidjumani davidjumani commented on code on Jul 21, 2026 13:54 UTC
    Code Review
    test/e2e/tests/apivalidation/apivalidation.go:1
    @@ -491,6 +491,22 @@ spec:
     `,
     			wantErrors: []string{"statPrefix can only be used when targeting HTTPRoute or GRPCRoute resources"},
     		},
    +		{
    +			name: "TrafficPolicy: empty requestMirror is rejected",
    +			input: `---
    +apiVersion: gateway.kgateway.dev/v1alpha1
    +kind: TrafficPolicy
    +metadata:
    +  name: traffic-policy-request-mirror-empty
    +spec:
    +  targetRefs:
    +  - group: gateway.networking.k8s.io
    +    kind: HTTPRoute
    +    name: test-route
    +  requestMirror: {}
    +`,
    +			wantErrors: []string{"requestMirror in body should have at least 1 properties"},

    What is the purpose of this test?

    JCigan JCigan commented on code on Jul 21, 2026 14:08 UTC
    Code Review
    test/e2e/tests/apivalidation/apivalidation.go:1
    @@ -491,6 +491,22 @@ spec:
     `,
     			wantErrors: []string{"statPrefix can only be used when targeting HTTPRoute or GRPCRoute resources"},
     		},
    +		{
    +			name: "TrafficPolicy: empty requestMirror is rejected",
    +			input: `---
    +apiVersion: gateway.kgateway.dev/v1alpha1
    +kind: TrafficPolicy
    +metadata:
    +  name: traffic-policy-request-mirror-empty
    +spec:
    +  targetRefs:
    +  - group: gateway.networking.k8s.io
    +    kind: HTTPRoute
    +    name: test-route
    +  requestMirror: {}
    +`,
    +			wantErrors: []string{"requestMirror in body should have at least 1 properties"},

    Good callout. The idea when I wrote it was to validate that MinProperties=1 is enforced, but looking around our codebase more, it looks like we don't really test the basic functionality of kubebuilder like that, and it makes less sense to do so on principle the more I think about it. I will just remove this one.

    JCigan JCigan commented on code on Jul 21, 2026 14:25 UTC
    Code Review
    api/v1alpha1/kgateway/traffic_policy_types.go:1
    @@ -90,6 +90,12 @@ type TrafficPolicySpec struct {
     	// +optional
     	HeaderModifiers *shared.HeaderModifiers `json:"headerModifiers,omitempty"`
     
    +	// RequestMirror configures the behavior of request mirrors defined by
    +	// HTTPRoute or GRPCRoute RequestMirror filters. It does not create request mirrors.
    +	// If a targeted route has no request mirrors, this configuration has no effect.
    +	// +optional
    +	RequestMirror *RequestMirrorPolicy `json:"requestMirror,omitempty"`

    I will take a bit to look further into this, because on an initial look, I'm not sure if I'd even have to change anything at code-level to make this toggle applicable to Gateways as well. I think you're right that it should be applicable to Gateways too and that, whether I'm changing the implementation or not, there needs to be verbiage in some combo of code, comments, and tests (plus the PR description) clarifying that use case is supported. Will get back to this after looking more deeply into it

    JCigan JCigan commented on code on Jul 21, 2026 14:53 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    I was looking at the implementations for Timeout and Retry too when I started this, because they also use the pattern you cited from AutoHostRewrite. This is going to take a long look, because this goes pretty deep in the weeds of Envoy.

    The field we're using for this toggle is just an unwrapped bool, see here, unlike the other fields we're using from this file, like AutoHostRewrite (see here), which is a more idiomatic wrapped bool using google.protobuf.BoolValue. And my understanding is that the difference in kgateway between those is that, with an unwrapped bool, there is no nil value where someone didn't declare a value for the field, it's just false, whereas with a wrapped bool the fact it was nil is preserved.

    Where I need to see if this becomes a problem is if, as addressed in your earlier comment and my reply, we're supporting this being configurable at Gateway level. I want to see how it would behave if we have an explicit, non-nil false at Route level with a true at the parent Gateway level. I think there's a chance that the treatment of that could be wonky, because we'd want it to preserve an explicit false but not to preserve a nil false. Let me validate rather than guessing, though.

    JCigan JCigan commented on code on Jul 21, 2026 18:10 UTC
    Code Review
    api/v1alpha1/kgateway/traffic_policy_types.go:1
    @@ -90,6 +90,12 @@ type TrafficPolicySpec struct {
     	// +optional
     	HeaderModifiers *shared.HeaderModifiers `json:"headerModifiers,omitempty"`
     
    +	// RequestMirror configures the behavior of request mirrors defined by
    +	// HTTPRoute or GRPCRoute RequestMirror filters. It does not create request mirrors.
    +	// If a targeted route has no request mirrors, this configuration has no effect.
    +	// +optional
    +	RequestMirror *RequestMirrorPolicy `json:"requestMirror,omitempty"`

    Working on pushing up a next revision. I have a golden test case (actually already did, but am making it clearer) that will assert that this works at Gateway level, and am making the verbiage clearer around the use case. Will also update the PR description after I push that revision up

    JCigan JCigan commented on code on Jul 21, 2026 19:01 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    So I did some manual validation both with the current code, and with it implemented in a way that mimicked the approach used in AutoHostRewrite. That approach worked in every case except one - the case with a Route-level false and a Gateway-level true, where the false at Route level indeed got overwritten. I could add details of this validation if you like, I put all of the commands and output into my Notes app, but wasn't sure if that were necessary. So I believe we have to keep the current approach in the next revision.

    I'll leave this comment thread unresolved just in case reviewers want evidence of that validation.

    JCigan JCigan commented on code on Jul 21, 2026 19:03 UTC
    Code Review
    api/v1alpha1/kgateway/traffic_policy_types.go:1
    @@ -225,6 +231,18 @@ type TrafficPolicySpec struct {
     	StatPrefix *string `json:"statPrefix,omitempty"`
     }
     
    +// RequestMirrorPolicy configures implementation-specific behavior for request mirrors.
    +// +kubebuilder:validation:MinProperties=1
    +type RequestMirrorPolicy struct {
    +	// DisableShadowHostSuffixAppend controls whether Envoy appends the "-shadow"
    +	// suffix to the Host or :authority header of mirrored requests.
    +	// When true, the original Host or :authority header is preserved.
    +	// When false, Envoy appends the suffix. When unset, the existing mirror

    Thanks, updated this portion

    davidjumani davidjumani commented on code on Jul 21, 2026 20:07 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    Is this the same case with retries and timeouts as well? How are they handled if defined at the gateway level ?

    JCigan JCigan commented on code on Jul 21, 2026 20:28 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    Because those fields Retry and Timeout are nilable (this is determined at Envoy level, we can't control it), a nil value is treated as distinct from an explicit false, and only a nil value at Route level will be overwritten, not an explicit false.

    We have an existing golden test case for Timeouts that should assert this: https://github.com/kgateway-dev/kgateway/blob/main/pkg/kgateway/translator/gateway/testutils/inputs/traffic-policy/timeout-gateway.yaml#L67.

    A quote from formal docs I consulted while digging into how to answer your prior comment that may help - like I said this is pretty deep in the weeds:

    Note that for implicit-presence scalar fields, once a message is parsed there’s no way of telling whether that field was explicitly set to the default value (for example whether a boolean was set to false) or just not set at all: you should bear this in mind when defining your message types. For example, don’t have a boolean that switches on some behavior when set to false if you don’t want that behavior to also happen by default. Also note that if a scalar message field is set to its default, the value will not be serialized on the wire. If a float or double value is set to +0 it will not be serialized, but -0 is considered distinct and will be serialized.

    This would apply to the type of field used for DisableShadowHostSuffixAppend in Envoy. Source link.

    I didn't find quite a good single quote from this doc for the handling of wrapped bools, but the salient point from this doc page is that field absence is handled in a distinct way from just a false bool value.

    ymesika ymesika approved these changes on Jul 22, 2026 07:33 UTC
    Approved Reviewer

    LGTM.
    All review comments addressed, thanks.

    JCigan JCigan commented on code on Jul 23, 2026 16:30 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    So an update on this - I tried a style that I hope is a bit cleaner, where it is now keying by out.GetName() and map[string]struct{}. David and I had discussed whether we could key by filter chain name - we cannot, as mirror precedence is per-route, and a chain can contain many routes. Because we are only passing a pointer to the route, by my understanding of how Go handles this, there should not be a memory issue involved in passing it, as we aren't parsing the whole route. But hopefully things look a bit cleaner now, in the updated code.

    andy-fong andy-fong commented on code on Jul 28, 2026 14:01 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/request_mirror.go:1
    @@ -0,0 +1,69 @@
    +package trafficpolicy
    +
    +import (
    +	envoyroutev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
    +
    +	"github.com/kgateway-dev/kgateway/v2/api/v1alpha1/kgateway"
    +)
    +
    +type requestMirrorIR struct {
    +	disableShadowHostSuffixAppend *bool
    +}
    +
    +var _ PolicySubIR = &requestMirrorIR{}
    +
    +func (r *requestMirrorIR) Equals(other PolicySubIR) bool {
    +	otherRequestMirror, ok := other.(*requestMirrorIR)
    +	if !ok {
    +		return false
    +	}
    +	if r == nil || otherRequestMirror == nil {
    +		return r == nil && otherRequestMirror == nil
    +	}
    +	if r.disableShadowHostSuffixAppend == nil || otherRequestMirror.disableShadowHostSuffixAppend == nil {
    +		return r.disableShadowHostSuffixAppend == nil && otherRequestMirror.disableShadowHostSuffixAppend == nil
    +	}
    +	return *r.disableShadowHostSuffixAppend == *otherRequestMirror.disableShadowHostSuffixAppend
    +}
    +
    +// Validate performs validation on the request mirror component. The API schema
    +// validates that at least one setting is present, so no IR validation is needed.
    +func (r *requestMirrorIR) Validate() error { return nil }
    +
    +// constructRequestMirror constructs the request mirror policy IR from the policy specification.
    +func constructRequestMirror(spec kgateway.TrafficPolicySpec, out *trafficPolicySpecIr) {
    +	if spec.RequestMirror == nil {
    +		return
    +	}
    +
    +	out.requestMirror = &requestMirrorIR{}
    +	if spec.RequestMirror.DisableShadowHostSuffixAppend != nil {
    +		disableShadowHostSuffixAppend := *spec.RequestMirror.DisableShadowHostSuffixAppend
    +		out.requestMirror.disableShadowHostSuffixAppend = &disableShadowHostSuffixAppend
    +	}
    +}
    +
    +func (p *trafficPolicyPluginGwPass) applyRequestMirror(requestMirror *requestMirrorIR, out *envoyroutev3.Route) {
    +	if requestMirror == nil || requestMirror.disableShadowHostSuffixAppend == nil || out == nil || out.GetRoute() == nil {
    +		return
    +	}
    +
    +	// Route policies run before listener and Gateway policies. Track routes (by name) that a policy has

    so, I assume listener policies get run before gateway? I don't see a test applying the new policy at listener level to override gateway level setting or route level overriding listener level setting. Can this be applied at vhost level as well? If yes, https listener should also be tested.
    The complication is similar to the retry policy https://github.com/kgateway-dev/kgateway/pull/14360, maybe compare that PR to this and see if we need anything similar to that PR.

    Sorry I am a bit vague. I remember it's complicated but not all the details.

    andy-fong andy-fong requested changes on Jul 28, 2026 14:01 UTC
    Changes Requested Reviewer

    Requested changes.

    JCigan JCigan commented on code on Jul 28, 2026 16:34 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/request_mirror.go:1
    @@ -0,0 +1,69 @@
    +package trafficpolicy
    +
    +import (
    +	envoyroutev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
    +
    +	"github.com/kgateway-dev/kgateway/v2/api/v1alpha1/kgateway"
    +)
    +
    +type requestMirrorIR struct {
    +	disableShadowHostSuffixAppend *bool
    +}
    +
    +var _ PolicySubIR = &requestMirrorIR{}
    +
    +func (r *requestMirrorIR) Equals(other PolicySubIR) bool {
    +	otherRequestMirror, ok := other.(*requestMirrorIR)
    +	if !ok {
    +		return false
    +	}
    +	if r == nil || otherRequestMirror == nil {
    +		return r == nil && otherRequestMirror == nil
    +	}
    +	if r.disableShadowHostSuffixAppend == nil || otherRequestMirror.disableShadowHostSuffixAppend == nil {
    +		return r.disableShadowHostSuffixAppend == nil && otherRequestMirror.disableShadowHostSuffixAppend == nil
    +	}
    +	return *r.disableShadowHostSuffixAppend == *otherRequestMirror.disableShadowHostSuffixAppend
    +}
    +
    +// Validate performs validation on the request mirror component. The API schema
    +// validates that at least one setting is present, so no IR validation is needed.
    +func (r *requestMirrorIR) Validate() error { return nil }
    +
    +// constructRequestMirror constructs the request mirror policy IR from the policy specification.
    +func constructRequestMirror(spec kgateway.TrafficPolicySpec, out *trafficPolicySpecIr) {
    +	if spec.RequestMirror == nil {
    +		return
    +	}
    +
    +	out.requestMirror = &requestMirrorIR{}
    +	if spec.RequestMirror.DisableShadowHostSuffixAppend != nil {
    +		disableShadowHostSuffixAppend := *spec.RequestMirror.DisableShadowHostSuffixAppend
    +		out.requestMirror.disableShadowHostSuffixAppend = &disableShadowHostSuffixAppend
    +	}
    +}
    +
    +func (p *trafficPolicyPluginGwPass) applyRequestMirror(requestMirror *requestMirrorIR, out *envoyroutev3.Route) {
    +	if requestMirror == nil || requestMirror.disableShadowHostSuffixAppend == nil || out == nil || out.GetRoute() == nil {
    +		return
    +	}
    +
    +	// Route policies run before listener and Gateway policies. Track routes (by name) that a policy has

    Thanks - let me read over that PR and think about this before giving a full answer.

    JCigan JCigan commented on code on Jul 29, 2026 00:29 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/request_mirror.go:1
    @@ -0,0 +1,69 @@
    +package trafficpolicy
    +
    +import (
    +	envoyroutev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
    +
    +	"github.com/kgateway-dev/kgateway/v2/api/v1alpha1/kgateway"
    +)
    +
    +type requestMirrorIR struct {
    +	disableShadowHostSuffixAppend *bool
    +}
    +
    +var _ PolicySubIR = &requestMirrorIR{}
    +
    +func (r *requestMirrorIR) Equals(other PolicySubIR) bool {
    +	otherRequestMirror, ok := other.(*requestMirrorIR)
    +	if !ok {
    +		return false
    +	}
    +	if r == nil || otherRequestMirror == nil {
    +		return r == nil && otherRequestMirror == nil
    +	}
    +	if r.disableShadowHostSuffixAppend == nil || otherRequestMirror.disableShadowHostSuffixAppend == nil {
    +		return r.disableShadowHostSuffixAppend == nil && otherRequestMirror.disableShadowHostSuffixAppend == nil
    +	}
    +	return *r.disableShadowHostSuffixAppend == *otherRequestMirror.disableShadowHostSuffixAppend
    +}
    +
    +// Validate performs validation on the request mirror component. The API schema
    +// validates that at least one setting is present, so no IR validation is needed.
    +func (r *requestMirrorIR) Validate() error { return nil }
    +
    +// constructRequestMirror constructs the request mirror policy IR from the policy specification.
    +func constructRequestMirror(spec kgateway.TrafficPolicySpec, out *trafficPolicySpecIr) {
    +	if spec.RequestMirror == nil {
    +		return
    +	}
    +
    +	out.requestMirror = &requestMirrorIR{}
    +	if spec.RequestMirror.DisableShadowHostSuffixAppend != nil {
    +		disableShadowHostSuffixAppend := *spec.RequestMirror.DisableShadowHostSuffixAppend
    +		out.requestMirror.disableShadowHostSuffixAppend = &disableShadowHostSuffixAppend
    +	}
    +}
    +
    +func (p *trafficPolicyPluginGwPass) applyRequestMirror(requestMirror *requestMirrorIR, out *envoyroutev3.Route) {
    +	if requestMirror == nil || requestMirror.disableShadowHostSuffixAppend == nil || out == nil || out.GetRoute() == nil {
    +		return
    +	}
    +
    +	// Route policies run before listener and Gateway policies. Track routes (by name) that a policy has

    Yes, listener policies do get run before gateway policies. But you're completely correct that the listener level wasn't covered before, and I'm fixing that with a commit I am pushing up shortly.

    I did compare against #14360 and concluded that this PR, as it stood, was already using the generalized per-route fanout for retries introduced in that PR. Gateway policies flow through ApplyRouteConfigPlugin, listener policies flow through ApplyVhostPlugin, and both of them call handlePerRoutePolicies for each route covered. So I don't think any bigger structural change is needed for this PR on that account.

    I am adding a listener-scoped test case and a new HTTPS golden test case, because that HTTPS listener coverage was also a good callout. Thanks again

    JCigan JCigan commented on code on Jul 29, 2026 18:51 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/request_mirror.go:1
    @@ -0,0 +1,69 @@
    +package trafficpolicy
    +
    +import (
    +	envoyroutev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
    +
    +	"github.com/kgateway-dev/kgateway/v2/api/v1alpha1/kgateway"
    +)
    +
    +type requestMirrorIR struct {
    +	disableShadowHostSuffixAppend *bool
    +}
    +
    +var _ PolicySubIR = &requestMirrorIR{}
    +
    +func (r *requestMirrorIR) Equals(other PolicySubIR) bool {
    +	otherRequestMirror, ok := other.(*requestMirrorIR)
    +	if !ok {
    +		return false
    +	}
    +	if r == nil || otherRequestMirror == nil {
    +		return r == nil && otherRequestMirror == nil
    +	}
    +	if r.disableShadowHostSuffixAppend == nil || otherRequestMirror.disableShadowHostSuffixAppend == nil {
    +		return r.disableShadowHostSuffixAppend == nil && otherRequestMirror.disableShadowHostSuffixAppend == nil
    +	}
    +	return *r.disableShadowHostSuffixAppend == *otherRequestMirror.disableShadowHostSuffixAppend
    +}
    +
    +// Validate performs validation on the request mirror component. The API schema
    +// validates that at least one setting is present, so no IR validation is needed.
    +func (r *requestMirrorIR) Validate() error { return nil }
    +
    +// constructRequestMirror constructs the request mirror policy IR from the policy specification.
    +func constructRequestMirror(spec kgateway.TrafficPolicySpec, out *trafficPolicySpecIr) {
    +	if spec.RequestMirror == nil {
    +		return
    +	}
    +
    +	out.requestMirror = &requestMirrorIR{}
    +	if spec.RequestMirror.DisableShadowHostSuffixAppend != nil {
    +		disableShadowHostSuffixAppend := *spec.RequestMirror.DisableShadowHostSuffixAppend
    +		out.requestMirror.disableShadowHostSuffixAppend = &disableShadowHostSuffixAppend
    +	}
    +}
    +
    +func (p *trafficPolicyPluginGwPass) applyRequestMirror(requestMirror *requestMirrorIR, out *envoyroutev3.Route) {
    +	if requestMirror == nil || requestMirror.disableShadowHostSuffixAppend == nil || out == nil || out.GetRoute() == nil {
    +		return
    +	}
    +
    +	// Route policies run before listener and Gateway policies. Track routes (by name) that a policy has

    The changes have now been pushed up, resolving for now

    JCigan JCigan commented on code on Aug 03, 2026 20:23 UTC
    Code Review
    pkg/kgateway/extensions2/plugins/trafficpolicy/traffic_policy_plugin.go:1
    @@ -262,6 +267,7 @@ type trafficPolicyPluginGwPass struct {
     	corsInChain              map[string]*corsv3.Cors
     	csrfInChain              map[string]*envoy_csrf_v3.CsrfPolicy
     	headerMutationInChain    map[string]*header_mutationv3.HeaderMutationPerRoute
    +	requestMirrorConfigured  map[*envoyroutev3.Route]struct{}

    Marking as resolved for now, as there's been no further discussion on this with the subsequent reviewers and they seem fine with the new direction, but feel free to unresolve if this is still up for review when you next look and it remains a sticking point.

    andy-fong andy-fong approved these changes on Aug 14, 2026 20:41 UTC
    Approved Reviewer

    Approved these changes.

    andy-fong andy-fong approved these changes on Aug 14, 2026 21:17 UTC
    Approved Reviewer

    Approved these changes.

    JCigan JCigan commented on Aug 14, 2026 21:48 UTC
    Author

    /merge

    JCigan JCigan commented on Aug 17, 2026 17:02 UTC
    Author

    /merge

    Reviewers
    Assignees
    JCigan JCigan
    Labels
    risk: low confidence: 74.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 62.1% (MEDIUM) · Higher = larger blast radius
    62.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 74.9% · Lower = rushed or shallow review
    74.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 15.6% · Safe to merge
    15.6%