From 6dd5cf35635ec75eb71b240cfbedec67a7a81fb6 Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Tue, 12 May 2026 17:30:07 -0400 Subject: [PATCH 1/8] feat: implement Gateway API routing class and solver Signed-off-by: Badre Tejado-Imam --- .../devworkspaceoperatorconfig_types.go | 25 + .../v1alpha1/devworkspacerouting_types.go | 1 + .../v1alpha1/zz_generated.deepcopy.go | 25 + .../devworkspacerouting_controller.go | 28 + .../devworkspacerouting_controller_test.go | 233 + .../solvers/gateway_api_solver.go | 332 + .../devworkspacerouting/solvers/solver.go | 7 +- .../devworkspacerouting/suite_test.go | 5 + .../devworkspacerouting/sync_httproutes.go | 109 + .../gateway.networking.k8s.io_httproutes.yaml | 5528 +++++++++++++++++ .../devworkspacerouting/util_test.go | 15 + deploy/templates/components/rbac/role.yaml | 6 + ...evfile.io_devworkspaceoperatorconfigs.yaml | 26 + go.mod | 3 +- go.sum | 6 +- 15 files changed, 6345 insertions(+), 4 deletions(-) create mode 100644 controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go create mode 100644 controllers/controller/devworkspacerouting/sync_httproutes.go create mode 100644 controllers/controller/devworkspacerouting/testdata/gateway.networking.k8s.io_httproutes.yaml diff --git a/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go b/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go index 9bd759c7f..9a845d1ca 100644 --- a/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go +++ b/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go @@ -120,6 +120,25 @@ type BackupCronJobConfig struct { BackoffLimit *int32 `json:"backoffLimit,omitempty"` } +// GatewayReference defines a reference to a Gateway API Gateway resource +// that HTTPRoutes should attach to via parentRefs. +type GatewayReference struct { + // Name is the name of the Gateway resource + // +kubebuilder:validation:Required + Name string `json:"name"` + // Namespace is the namespace of the Gateway resource. + // If not specified, HTTPRoutes will reference a Gateway in the same namespace + // as the DevWorkspace. + // +kubebuilder:validation:Optional + Namespace *string `json:"namespace,omitempty"` + // GatewayClassName is the name of the GatewayClass to use. + // This is used for validation and informational purposes. + // Defaults to "nginx" if not specified. + // +kubebuilder:validation:Optional + // +kubebuilder:default:="nginx" + GatewayClassName string `json:"gatewayClassName,omitempty"` +} + type RoutingConfig struct { // DefaultRoutingClass specifies the routingClass to be used when a DevWorkspace // specifies an empty `.spec.routingClass`. Supported routingClasses can be defined @@ -145,6 +164,12 @@ type RoutingConfig struct { // TLSCertificateConfigmapRef defines the name and namespace of the configmap with a certificate to inject into the // HTTP client. TLSCertificateConfigmapRef *ConfigmapReference `json:"tlsCertificateConfigmapRef,omitempty"` + // GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + // should attach to when using the 'gateway-api' routing class. This field is required + // when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + // by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + // +kubebuilder:validation:Optional + GatewayRef *GatewayReference `json:"gatewayRef,omitempty"` } // OverrideConfig defines configuration options for controlling which fields are restricted diff --git a/apis/controller/v1alpha1/devworkspacerouting_types.go b/apis/controller/v1alpha1/devworkspacerouting_types.go index daa0f6a7c..c8264e33f 100644 --- a/apis/controller/v1alpha1/devworkspacerouting_types.go +++ b/apis/controller/v1alpha1/devworkspacerouting_types.go @@ -40,6 +40,7 @@ const ( DevWorkspaceRoutingCluster DevWorkspaceRoutingClass = "cluster" DevWorkspaceRoutingClusterTLS DevWorkspaceRoutingClass = "cluster-tls" DevWorkspaceRoutingWebTerminal DevWorkspaceRoutingClass = "web-terminal" + DevWorkspaceRoutingGatewayAPI DevWorkspaceRoutingClass = "gateway-api" ) // DevWorkspaceRoutingStatus defines the observed state of DevWorkspaceRouting diff --git a/apis/controller/v1alpha1/zz_generated.deepcopy.go b/apis/controller/v1alpha1/zz_generated.deepcopy.go index a576d4a0d..6815ddc7f 100644 --- a/apis/controller/v1alpha1/zz_generated.deepcopy.go +++ b/apis/controller/v1alpha1/zz_generated.deepcopy.go @@ -425,6 +425,26 @@ func (in ExposedEndpointList) DeepCopy() ExposedEndpointList { return *out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GatewayReference) DeepCopyInto(out *GatewayReference) { + *out = *in + if in.Namespace != nil { + in, out := &in.Namespace, &out.Namespace + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewayReference. +func (in *GatewayReference) DeepCopy() *GatewayReference { + if in == nil { + return nil + } + out := new(GatewayReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *KeyNotFoundError) DeepCopyInto(out *KeyNotFoundError) { *out = *in @@ -781,6 +801,11 @@ func (in *RoutingConfig) DeepCopyInto(out *RoutingConfig) { *out = new(ConfigmapReference) **out = **in } + if in.GatewayRef != nil { + in, out := &in.GatewayRef, &out.GatewayRef + *out = new(GatewayReference) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RoutingConfig. diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index d16197185..8b2d6ba21 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -71,6 +71,7 @@ type DevWorkspaceRoutingReconciler struct { // +kubebuilder:rbac:groups=route.openshift.io,resources=routes,verbs=* // +kubebuidler:rbac:groups=route.openshift.io,resources=routes/status,verbs=get,list,watch // +kubebuilder:rbac:groups=route.openshift.io,resources=routes/custom-host,verbs=create +// +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=httproutes,verbs=* func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { reqLogger := r.Log.WithValues("Request.Namespace", req.Namespace, "Request.Name", req.Name) @@ -214,6 +215,16 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. routes[idx].Annotations = maputils.Append(routes[idx].Annotations, constants.DevWorkspaceRestrictedAccessAnnotation, restrictedAccess) } } + httpRoutes := routingObjects.HTTPRoutes + for idx := range httpRoutes { + err := controllerutil.SetControllerReference(instance, &httpRoutes[idx], r.Scheme) + if err != nil { + return reconcile.Result{}, err + } + if setRestrictedAccess { + httpRoutes[idx].Annotations = maputils.Append(httpRoutes[idx].Annotations, constants.DevWorkspaceRestrictedAccessAnnotation, restrictedAccess) + } + } servicesInSync, clusterServices, err := r.syncServices(ctx, instance, services) if err != nil { @@ -283,6 +294,23 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. clusterRoutingObj.Ingresses = clusterIngresses } + // Sync HTTPRoutes if using gateway-api routing class + if len(httpRoutes) > 0 { + httpRoutesInSync, clusterHTTPRoutes, err := r.syncHTTPRoutes(instance, httpRoutes) + if err != nil { + failError := &sync.UnrecoverableSyncError{} + if errors.As(err, &failError) { + return reconcile.Result{}, r.markRoutingFailed(instance, err.Error()) + } + reqLogger.Error(err, "Error syncing HTTPRoutes") + return reconcile.Result{Requeue: true}, r.reconcileStatus(instance, nil, nil, false, "Preparing HTTPRoutes") + } else if !httpRoutesInSync { + reqLogger.Info("HTTPRoutes not in sync") + return reconcile.Result{Requeue: true}, r.reconcileStatus(instance, nil, nil, false, "Preparing HTTPRoutes") + } + clusterRoutingObj.HTTPRoutes = clusterHTTPRoutes + } + exposedEndpoints, endpointsAreReady, err := solver.GetExposedEndpoints(instance.Spec.Endpoints, clusterRoutingObj) if err != nil { reqLogger.Error(err, "Could not get exposed endpoints for devworkspace") diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go index b6e859d69..568c945a1 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go @@ -30,6 +30,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" "github.com/devfile/devworkspace-operator/controllers/controller/devworkspacerouting" @@ -417,6 +418,238 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { }, timeout, interval).Should(BeTrue(), "Route for non-exposed endpoint should not exist in cluster") }) }) + + Context("Gateway API - DevWorkspaceRouting Objects creation", func() { + gatewayName := "test-gateway" + gatewayNamespace := testNamespace + + BeforeEach(func() { + infrastructure.InitializeForTesting(infrastructure.Kubernetes) + // Configure operator with Gateway API settings + gatewayRefNamespace := gatewayNamespace + dwoc := testControllerCfg.DeepCopy() + dwoc.Routing = &controllerv1alpha1.RoutingConfig{ + ClusterHostSuffix: "test-environment-cluster-suffix", + DefaultRoutingClass: "gateway-api", + GatewayRef: &controllerv1alpha1.GatewayReference{ + Name: gatewayName, + Namespace: &gatewayRefNamespace, + GatewayClassName: "nginx", + }, + } + config.SetGlobalConfigForTesting(dwoc) + + // Create DevWorkspaceRouting with gateway-api routing class + mainAttributes := controllerv1alpha1.Attributes{} + mainAttributes.PutString("type", "main") + discoverableAttributes := controllerv1alpha1.Attributes{} + discoverableAttributes.PutBoolean(string(controllerv1alpha1.DiscoverableAttribute), true) + annotations := map[string]string{endpointAnnotationKey: endpointAnnotationValue} + + exposedEndpoint := controllerv1alpha1.Endpoint{ + Name: exposedEndPointName, + Exposure: controllerv1alpha1.PublicEndpointExposure, + Attributes: mainAttributes, + TargetPort: exposedTargetPort, + Annotations: annotations, + } + nonExposedEndpoint := controllerv1alpha1.Endpoint{ + Name: nonExposedEndpointName, + Exposure: controllerv1alpha1.NoneEndpointExposure, + TargetPort: nonExposedTargetPort, + } + discoverableEndpoint := controllerv1alpha1.Endpoint{ + Name: discoverableEndpointName, + Exposure: controllerv1alpha1.PublicEndpointExposure, + Attributes: discoverableAttributes, + TargetPort: discoverableTargetPort, + Annotations: annotations, + } + machineEndpointsMap := map[string]controllerv1alpha1.EndpointList{ + testMachineName: { + exposedEndpoint, + nonExposedEndpoint, + discoverableEndpoint, + }, + } + + dwr := &controllerv1alpha1.DevWorkspaceRouting{ + Spec: controllerv1alpha1.DevWorkspaceRoutingSpec{ + DevWorkspaceId: testWorkspaceID, + RoutingClass: controllerv1alpha1.DevWorkspaceRoutingGatewayAPI, + Endpoints: machineEndpointsMap, + PodSelector: map[string]string{ + constants.DevWorkspaceIDLabel: testWorkspaceID, + }, + }, + } + + dwr.SetName(devWorkspaceRoutingName) + dwr.SetNamespace(testNamespace) + + Expect(k8sClient.Create(ctx, dwr)).Should(Succeed()) + }) + + AfterEach(func() { + config.SetGlobalConfigForTesting(testControllerCfg) + deleteDevWorkspaceRouting(devWorkspaceRoutingName) + deleteService(common.ServiceName(testWorkspaceID), testNamespace) + deleteService(common.EndpointName(discoverableEndpointName), testNamespace) + deleteHTTPRoute(exposedEndPointName, testNamespace, false) + deleteHTTPRoute(exposedEndPointName, testNamespace, true) + deleteHTTPRoute(discoverableEndpointName, testNamespace, false) + deleteHTTPRoute(discoverableEndpointName, testNamespace, true) + }) + + It("Gets Ready Status with Gateway API", func() { + By("Checking DevWorkspaceRouting Status is updated to Ready") + dwrNamespacedName := namespacedName(devWorkspaceRoutingName, testNamespace) + createdDWR := &controllerv1alpha1.DevWorkspaceRouting{} + Eventually(func() (phase controllerv1alpha1.DevWorkspaceRoutingPhase, err error) { + if err := k8sClient.Get(ctx, dwrNamespacedName, createdDWR); err != nil { + return "", err + } + return createdDWR.Status.Phase, nil + }, timeout, interval).Should(Equal(controllerv1alpha1.RoutingReady), "DevWorkspaceRouting should have Ready phase") + Expect(createdDWR.Status.Message).ShouldNot(BeNil(), "Status message should be set for preparing DevWorkspaceRoutings") + Expect(createdDWR.Status.Message).Should(Equal("DevWorkspaceRouting prepared"), "Status message should indicate that the DevWorkspaceRouting is prepared") + }) + + It("Creates services", func() { + createdDWR := getExistingDevWorkspaceRouting(devWorkspaceRoutingName) + + By("Checking single service is created for all exposed endpoints") + createdService := &corev1.Service{} + serviceNamespacedName := namespacedName(common.ServiceName(testWorkspaceID), testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, serviceNamespacedName, createdService) + return err == nil + }, timeout, interval).Should(BeTrue(), "Service should exist in cluster") + Expect(createdService.Spec.Selector).Should(Equal(createdDWR.Spec.PodSelector), "Service should have pod selector from DevWorkspace metadata") + Expect(createdService.Labels).Should(Equal(ExpectedLabels), "Service should contain DevWorkspace ID label") + expectedOwnerReference := devWorkspaceRoutingOwnerRef(createdDWR) + Expect(createdService.OwnerReferences).Should(ContainElement(expectedOwnerReference), "Service should be owned by DevWorkspaceRouting") + + By("Checking service has expected ports") + var expectedServicePorts []corev1.ServicePort + expectedServicePorts = append(expectedServicePorts, corev1.ServicePort{ + Name: common.EndpointName(exposedEndPointName), + Protocol: corev1.ProtocolTCP, + Port: int32(exposedTargetPort), + TargetPort: intstr.FromInt(exposedTargetPort), + }) + + expectedServicePorts = append(expectedServicePorts, corev1.ServicePort{ + Name: common.EndpointName(discoverableEndpointName), + Protocol: corev1.ProtocolTCP, + Port: int32(discoverableTargetPort), + TargetPort: intstr.FromInt(discoverableTargetPort), + }) + + Expect(len(createdService.Spec.Ports)).Should(Equal(2), fmt.Sprintf("Only two ports should be exposed: %s and %s", exposedEndPointName, discoverableEndpointName)) + Expect(createdService.Spec.Ports).Should(Equal(expectedServicePorts), "Service should contain expected ports") + + By("Checking service is created for discoverable endpoint") + discoverableEndpointService := &corev1.Service{} + discoverableEndpointServiceNamespacedName := namespacedName(common.EndpointName(discoverableEndpointName), testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, discoverableEndpointServiceNamespacedName, discoverableEndpointService) + return err == nil + }, timeout, interval).Should(BeTrue(), "Service for discoverable endpoint should exist in cluster") + Expect(len(discoverableEndpointService.Spec.Ports)).Should(Equal(1), "Service for discoverable endpoint should only have a single port") + Expect(discoverableEndpointService.Spec.Ports[0].Port).Should(Equal(int32(discoverableTargetPort))) + Expect(discoverableEndpointService.Spec.Ports[0].TargetPort).Should(Equal(intstr.FromInt(discoverableTargetPort))) + Expect(discoverableEndpointService.ObjectMeta.Annotations).Should(HaveKeyWithValue(constants.DevWorkspaceDiscoverableServiceAnnotation, "true"), "Service type should have discoverable service annotation") + }) + + It("Creates HTTPRoutes", func() { + createdDWR := getExistingDevWorkspaceRouting(devWorkspaceRoutingName) + + By("Checking HTTPS HTTPRoute is created for exposed endpoint") + createdHTTPRoute := gwapiv1.HTTPRoute{} + httpRouteNamespacedName := namespacedName(common.RouteName(testWorkspaceID, exposedEndPointName), testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, httpRouteNamespacedName, &createdHTTPRoute) + return err == nil + }, timeout, interval).Should(BeTrue(), "HTTPRoute should exist in cluster") + + Expect(createdHTTPRoute.Labels).Should(Equal(ExpectedLabels), "HTTPRoute should contain DevWorkspace ID label") + expectedOwnerReference := devWorkspaceRoutingOwnerRef(createdDWR) + Expect(createdHTTPRoute.OwnerReferences).Should(ContainElement(expectedOwnerReference), "HTTPRoute should be owned by DevWorkspaceRouting") + Expect(createdHTTPRoute.ObjectMeta.Annotations).Should(HaveKeyWithValue(constants.DevWorkspaceEndpointNameAnnotation, exposedEndPointName), "HTTPRoute should have endpoint name annotation") + Expect(createdHTTPRoute.ObjectMeta.Annotations).Should(HaveKeyWithValue(endpointAnnotationKey, endpointAnnotationValue), "HTTPRoute should have annotation from endpoint") + + By("Checking HTTPRoute has correct ParentRefs pointing to Gateway") + Expect(len(createdHTTPRoute.Spec.ParentRefs)).Should(Equal(1), "HTTPRoute should have one parent reference") + parentRef := createdHTTPRoute.Spec.ParentRefs[0] + Expect(string(parentRef.Name)).Should(Equal(gatewayName), "HTTPRoute should reference the configured Gateway") + Expect(*parentRef.Namespace).Should(Equal(gwapiv1.Namespace(gatewayNamespace)), "HTTPRoute should reference Gateway in correct namespace") + Expect(*parentRef.Port).Should(Equal(gwapiv1.PortNumber(443)), "HTTPS HTTPRoute should reference port 443") + + By("Checking HTTPRoute points to service backend") + createdService := &corev1.Service{} + serviceNamespacedName := namespacedName(common.ServiceName(testWorkspaceID), testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, serviceNamespacedName, createdService) + return err == nil + }, timeout, interval).Should(BeTrue(), "Service should exist in cluster") + + Expect(len(createdHTTPRoute.Spec.Rules)).Should(BeNumerically(">", 0), "HTTPRoute should have at least one rule") + rule := createdHTTPRoute.Spec.Rules[0] + Expect(len(rule.BackendRefs)).Should(Equal(1), "HTTPRoute rule should have one backend reference") + backendRef := rule.BackendRefs[0] + Expect(string(backendRef.Name)).Should(Equal(createdService.Name), "HTTPRoute backend should reference the service") + Expect(*backendRef.Port).Should(Equal(gwapiv1.PortNumber(exposedTargetPort)), "HTTPRoute backend port should match endpoint target port") + + By("Checking HTTP redirect HTTPRoute is created") + httpRedirectRoute := gwapiv1.HTTPRoute{} + httpRedirectRouteNamespacedName := namespacedName(common.RouteName(testWorkspaceID, exposedEndPointName)+"-http-redirect", testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, httpRedirectRouteNamespacedName, &httpRedirectRoute) + return err == nil + }, timeout, interval).Should(BeTrue(), "HTTP redirect HTTPRoute should exist in cluster") + + Expect(httpRedirectRoute.Labels).Should(Equal(ExpectedLabels), "HTTP redirect HTTPRoute should contain DevWorkspace ID label") + Expect(httpRedirectRoute.OwnerReferences).Should(ContainElement(expectedOwnerReference), "HTTP redirect HTTPRoute should be owned by DevWorkspaceRouting") + Expect(len(httpRedirectRoute.Spec.ParentRefs)).Should(Equal(1), "HTTP redirect HTTPRoute should have one parent reference") + httpParentRef := httpRedirectRoute.Spec.ParentRefs[0] + Expect(*httpParentRef.Port).Should(Equal(gwapiv1.PortNumber(80)), "HTTP redirect HTTPRoute should reference port 80") + + By("Checking HTTP redirect HTTPRoute has redirect filter") + Expect(len(httpRedirectRoute.Spec.Rules)).Should(BeNumerically(">", 0), "HTTP redirect HTTPRoute should have at least one rule") + httpRule := httpRedirectRoute.Spec.Rules[0] + Expect(len(httpRule.Filters)).Should(BeNumerically(">", 0), "HTTP redirect rule should have filters") + var hasRedirectFilter bool + for _, filter := range httpRule.Filters { + if filter.Type == gwapiv1.HTTPRouteFilterRequestRedirect { + hasRedirectFilter = true + Expect(filter.RequestRedirect).ShouldNot(BeNil(), "Redirect filter should have RequestRedirect configuration") + Expect(*filter.RequestRedirect.Scheme).Should(Equal(gwapiv1.HTTPSProtocolType), "Redirect should be to HTTPS") + Expect(*filter.RequestRedirect.StatusCode).Should(Equal(308), "Redirect should use 308 status code") + } + } + Expect(hasRedirectFilter).Should(BeTrue(), "HTTP redirect HTTPRoute should have a redirect filter") + + By("Checking HTTPRoutes are created for discoverable endpoint") + discoverableHTTPRoute := gwapiv1.HTTPRoute{} + discoverableHTTPRouteNN := namespacedName(common.RouteName(testWorkspaceID, discoverableEndpointName), testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, discoverableHTTPRouteNN, &discoverableHTTPRoute) + return err == nil + }, timeout, interval).Should(BeTrue(), "HTTPRoute for discoverable endpoint should exist in cluster") + Expect(discoverableHTTPRoute.Labels).Should(Equal(ExpectedLabels), "Discoverable HTTPRoute should contain DevWorkspace ID label") + Expect(discoverableHTTPRoute.OwnerReferences).Should(ContainElement(expectedOwnerReference), "Discoverable HTTPRoute should be owned by DevWorkspaceRouting") + Expect(discoverableHTTPRoute.ObjectMeta.Annotations).Should(HaveKeyWithValue(constants.DevWorkspaceEndpointNameAnnotation, discoverableEndpointName), "Discoverable HTTPRoute should have endpoint name annotation") + + By("Checking HTTPRoute is not created for non-exposed endpoint") + nonExposedHTTPRoute := gwapiv1.HTTPRoute{} + nonExposedHTTPRouteNamespacedName := namespacedName(common.RouteName(testWorkspaceID, nonExposedEndpointName), testNamespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, nonExposedHTTPRouteNamespacedName, &nonExposedHTTPRoute) + return k8sErrors.IsNotFound(err) + }, timeout, interval).Should(BeTrue(), "HTTPRoute for non-exposed endpoint should not exist in cluster") + }) + }) }) Context("Failure cases", func() { diff --git a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go new file mode 100644 index 000000000..5e6839201 --- /dev/null +++ b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go @@ -0,0 +1,332 @@ +// +// Copyright (c) 2019-2026 Red Hat, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package solvers + +import ( + "fmt" + + controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" + "github.com/devfile/devworkspace-operator/pkg/common" + "github.com/devfile/devworkspace-operator/pkg/config" + "github.com/devfile/devworkspace-operator/pkg/constants" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" +) + +// GatewayAPISolver exposes endpoints using Kubernetes Gateway API HTTPRoutes +// HTTPRoutes are attached to a Gateway specified in the operator configuration +type GatewayAPISolver struct{} + +var _ RoutingSolver = (*GatewayAPISolver)(nil) + +func (s *GatewayAPISolver) FinalizerRequired(*controllerv1alpha1.DevWorkspaceRouting) bool { + return false +} + +func (s *GatewayAPISolver) Finalize(*controllerv1alpha1.DevWorkspaceRouting) error { + return nil +} + +func (s *GatewayAPISolver) GetSpecObjects(routing *controllerv1alpha1.DevWorkspaceRouting, workspaceMeta DevWorkspaceMetadata) (RoutingObjects, error) { + routingObjects := RoutingObjects{} + + // Validate Gateway reference is configured + globalConfig := config.GetGlobalConfig() + if globalConfig.Routing == nil || globalConfig.Routing.GatewayRef == nil { + return routingObjects, &RoutingInvalid{"gateway-api routing requires .config.routing.gatewayRef to be set in operator config"} + } + + // Validate cluster host suffix + routingSuffix := globalConfig.Routing.ClusterHostSuffix + if routingSuffix == "" { + return routingObjects, &RoutingInvalid{"gateway-api routing requires .config.routing.clusterHostSuffix to be set in operator config"} + } + + spec := routing.Spec + + // Create Services (same as basic solver - HTTPRoutes route to Services) + services := getServicesForEndpoints(spec.Endpoints, workspaceMeta) + services = append(services, GetDiscoverableServicesForEndpoints(spec.Endpoints, workspaceMeta)...) + routingObjects.Services = services + + // Create HTTPRoutes for Gateway API + httpRoutes := s.getHTTPRoutesForSpec(globalConfig.Routing.GatewayRef, routing.Namespace, routingSuffix, spec.Endpoints, workspaceMeta) + routingObjects.HTTPRoutes = httpRoutes + + return routingObjects, nil +} + +func (s *GatewayAPISolver) getHTTPRoutesForSpec( + gatewayRef *controllerv1alpha1.GatewayReference, + routingNamespace string, + clusterHostSuffix string, + endpoints map[string]controllerv1alpha1.EndpointList, + workspaceMeta DevWorkspaceMetadata, +) []gwapiv1.HTTPRoute { + var httpRoutes []gwapiv1.HTTPRoute + + // Determine Gateway namespace - use same namespace as routing if not specified + gatewayNamespace := routingNamespace + if gatewayRef.Namespace != nil { + gatewayNamespace = *gatewayRef.Namespace + } + + for _, machineEndpoints := range endpoints { + for _, endpoint := range machineEndpoints { + if endpoint.Exposure != controllerv1alpha1.PublicEndpointExposure { + continue + } + + // Generate hostname using common naming function + endpointName := common.EndpointName(endpoint.Name) + hostname := common.EndpointHostname(clusterHostSuffix, workspaceMeta.DevWorkspaceId, endpointName, endpoint.TargetPort) + + // Create HTTP -> HTTPS redirect route (port 80) + httpRedirectRoute := s.createHTTPRedirectRoute( + gatewayRef, + gatewayNamespace, + hostname, + endpoint, + endpointName, + workspaceMeta, + ) + httpRoutes = append(httpRoutes, httpRedirectRoute) + + // Create HTTPS backend route (port 443) + httpsRoute := s.createHTTPSBackendRoute( + gatewayRef, + gatewayNamespace, + hostname, + endpoint, + endpointName, + workspaceMeta, + ) + httpRoutes = append(httpRoutes, httpsRoute) + } + } + + return httpRoutes +} + +func (s *GatewayAPISolver) createHTTPRedirectRoute( + gatewayRef *controllerv1alpha1.GatewayReference, + gatewayNamespace string, + hostname string, + endpoint controllerv1alpha1.Endpoint, + endpointName string, + workspaceMeta DevWorkspaceMetadata, +) gwapiv1.HTTPRoute { + routeName := fmt.Sprintf("%s-http-redirect", common.RouteName(workspaceMeta.DevWorkspaceId, endpointName)) + + httpsScheme := "https" + statusCode := 308 + + pathPrefix := gwapiv1.PathMatchPathPrefix + pathValue := "/" + + group := gwapiv1.Group(gwapiv1.GroupVersion.Group) + kind := gwapiv1.Kind("Gateway") + namespace := gwapiv1.Namespace(gatewayNamespace) + port := gwapiv1.PortNumber(80) + + annotations := map[string]string{ + constants.DevWorkspaceEndpointNameAnnotation: endpoint.Name, + } + for k, v := range endpoint.Annotations { + annotations[k] = v + } + + return gwapiv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: routeName, + Namespace: workspaceMeta.Namespace, + Labels: map[string]string{ + constants.DevWorkspaceIDLabel: workspaceMeta.DevWorkspaceId, + }, + Annotations: annotations, + }, + Spec: gwapiv1.HTTPRouteSpec{ + CommonRouteSpec: gwapiv1.CommonRouteSpec{ + ParentRefs: []gwapiv1.ParentReference{ + { + Group: &group, + Kind: &kind, + Namespace: &namespace, + Name: gwapiv1.ObjectName(gatewayRef.Name), + Port: &port, + }, + }, + }, + Hostnames: []gwapiv1.Hostname{gwapiv1.Hostname(hostname)}, + Rules: []gwapiv1.HTTPRouteRule{ + { + Matches: []gwapiv1.HTTPRouteMatch{ + { + Path: &gwapiv1.HTTPPathMatch{ + Type: &pathPrefix, + Value: &pathValue, + }, + }, + }, + Filters: []gwapiv1.HTTPRouteFilter{ + { + Type: gwapiv1.HTTPRouteFilterRequestRedirect, + RequestRedirect: &gwapiv1.HTTPRequestRedirectFilter{ + Scheme: &httpsScheme, + StatusCode: &statusCode, + }, + }, + }, + }, + }, + }, + } +} + +func (s *GatewayAPISolver) createHTTPSBackendRoute( + gatewayRef *controllerv1alpha1.GatewayReference, + gatewayNamespace string, + hostname string, + endpoint controllerv1alpha1.Endpoint, + endpointName string, + workspaceMeta DevWorkspaceMetadata, +) gwapiv1.HTTPRoute { + routeName := common.RouteName(workspaceMeta.DevWorkspaceId, endpointName) + + pathPrefix := gwapiv1.PathMatchPathPrefix + pathValue := "/" + + // 10 hour timeout (matching ingress2gateway output and long-running workspace sessions) + requestTimeout := gwapiv1.Duration("10h") + + group := gwapiv1.Group(gwapiv1.GroupVersion.Group) + kind := gwapiv1.Kind("Gateway") + namespace := gwapiv1.Namespace(gatewayNamespace) + httpsPort := gwapiv1.PortNumber(443) + servicePort := gwapiv1.PortNumber(endpoint.TargetPort) + + annotations := map[string]string{ + constants.DevWorkspaceEndpointNameAnnotation: endpoint.Name, + } + for k, v := range endpoint.Annotations { + annotations[k] = v + } + + return gwapiv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: routeName, + Namespace: workspaceMeta.Namespace, + Labels: map[string]string{ + constants.DevWorkspaceIDLabel: workspaceMeta.DevWorkspaceId, + }, + Annotations: annotations, + }, + Spec: gwapiv1.HTTPRouteSpec{ + CommonRouteSpec: gwapiv1.CommonRouteSpec{ + ParentRefs: []gwapiv1.ParentReference{ + { + Group: &group, + Kind: &kind, + Namespace: &namespace, + Name: gwapiv1.ObjectName(gatewayRef.Name), + Port: &httpsPort, + }, + }, + }, + Hostnames: []gwapiv1.Hostname{gwapiv1.Hostname(hostname)}, + Rules: []gwapiv1.HTTPRouteRule{ + { + Matches: []gwapiv1.HTTPRouteMatch{ + { + Path: &gwapiv1.HTTPPathMatch{ + Type: &pathPrefix, + Value: &pathValue, + }, + }, + }, + BackendRefs: []gwapiv1.HTTPBackendRef{ + { + BackendRef: gwapiv1.BackendRef{ + BackendObjectReference: gwapiv1.BackendObjectReference{ + Name: gwapiv1.ObjectName(common.ServiceName(workspaceMeta.DevWorkspaceId)), + Port: &servicePort, + }, + }, + }, + }, + Timeouts: &gwapiv1.HTTPRouteTimeouts{ + Request: &requestTimeout, + }, + }, + }, + }, + } +} + +func (s *GatewayAPISolver) GetExposedEndpoints( + endpoints map[string]controllerv1alpha1.EndpointList, + routingObj RoutingObjects) (exposedEndpoints map[string]controllerv1alpha1.ExposedEndpointList, ready bool, err error) { + + // For Gateway API, we can construct URLs immediately from HTTPRoutes + // Similar to how Ingresses work - the URL is determined by the hostname in the HTTPRoute spec + return getExposedEndpointsFromHTTPRoutes(endpoints, routingObj) +} + +// getExposedEndpointsFromHTTPRoutes extracts endpoint URLs from HTTPRoutes +func getExposedEndpointsFromHTTPRoutes( + endpoints map[string]controllerv1alpha1.EndpointList, + routingObj RoutingObjects) (exposedEndpoints map[string]controllerv1alpha1.ExposedEndpointList, ready bool, err error) { + + exposedEndpoints = map[string]controllerv1alpha1.ExposedEndpointList{} + ready = true + + // Iterate through endpoints and match them to HTTPRoutes by annotation + for componentName, endpointList := range endpoints { + for _, endpoint := range endpointList { + if endpoint.Exposure != controllerv1alpha1.PublicEndpointExposure { + continue + } + + // Find the HTTPRoute for this endpoint by matching the endpoint name annotation + var url string + for _, httpRoute := range routingObj.HTTPRoutes { + // Only check HTTPS routes (not HTTP redirects) - they're the actual backend routes + if httpRoute.Annotations[constants.DevWorkspaceEndpointNameAnnotation] == endpoint.Name { + if len(httpRoute.Spec.Rules) > 0 && len(httpRoute.Spec.Rules[0].BackendRefs) > 0 { + if len(httpRoute.Spec.Hostnames) > 0 { + hostname := string(httpRoute.Spec.Hostnames[0]) + // Use HTTPS scheme + url = fmt.Sprintf("https://%s%s", hostname, endpoint.Path) + break + } + } + } + } + + if url == "" { + ready = false + } + + exposedEndpoints[componentName] = append(exposedEndpoints[componentName], + controllerv1alpha1.ExposedEndpoint{ + Name: endpoint.Name, + Url: url, + Attributes: endpoint.Attributes, + }) + } + } + + return exposedEndpoints, ready, nil +} diff --git a/controllers/controller/devworkspacerouting/solvers/solver.go b/controllers/controller/devworkspacerouting/solvers/solver.go index edf3666bb..08e9cdacb 100644 --- a/controllers/controller/devworkspacerouting/solvers/solver.go +++ b/controllers/controller/devworkspacerouting/solvers/solver.go @@ -23,6 +23,7 @@ import ( networkingv1 "k8s.io/api/networking/v1" "sigs.k8s.io/controller-runtime/pkg/builder" "sigs.k8s.io/controller-runtime/pkg/client" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" "github.com/devfile/devworkspace-operator/pkg/infrastructure" @@ -32,6 +33,7 @@ type RoutingObjects struct { Services []corev1.Service Ingresses []networkingv1.Ingress Routes []routeV1.Route + HTTPRoutes []gwapiv1.HTTPRoute PodAdditions *controllerv1alpha1.PodAdditions } @@ -94,7 +96,8 @@ func (_ *SolverGetter) HasSolver(routingClass controllerv1alpha1.DevWorkspaceRou case controllerv1alpha1.DevWorkspaceRoutingBasic, controllerv1alpha1.DevWorkspaceRoutingCluster, controllerv1alpha1.DevWorkspaceRoutingClusterTLS, - controllerv1alpha1.DevWorkspaceRoutingWebTerminal: + controllerv1alpha1.DevWorkspaceRoutingWebTerminal, + controllerv1alpha1.DevWorkspaceRoutingGatewayAPI: return true default: return false @@ -114,6 +117,8 @@ func (_ *SolverGetter) GetSolver(client client.Client, routingClass controllerv1 return nil, fmt.Errorf("routing class %s only supported on OpenShift", routingClass) } return NewClusterSolver(client, true), nil + case controllerv1alpha1.DevWorkspaceRoutingGatewayAPI: + return &GatewayAPISolver{}, nil default: return nil, RoutingNotSupported } diff --git a/controllers/controller/devworkspacerouting/suite_test.go b/controllers/controller/devworkspacerouting/suite_test.go index dd3f0c06a..1b633b9f7 100644 --- a/controllers/controller/devworkspacerouting/suite_test.go +++ b/controllers/controller/devworkspacerouting/suite_test.go @@ -29,6 +29,7 @@ import ( "github.com/devfile/devworkspace-operator/controllers/controller/devworkspacerouting" "github.com/devfile/devworkspace-operator/controllers/controller/devworkspacerouting/solvers" routev1 "github.com/openshift/api/route/v1" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -89,6 +90,8 @@ var _ = BeforeSuite(func() { filepath.Join("..", "..", "..", "deploy", "templates", "crd", "bases"), // Required to register OpenShift route CRD in testing environment filepath.Join(".", "testdata", "route.crd.yaml"), + // Required to register Gateway API HTTPRoute CRD in testing environment + filepath.Join(".", "testdata", "gateway.networking.k8s.io_httproutes.yaml"), }, ErrorIfCRDPathMissing: true, BinaryAssetsDirectory: filepath.Join("..", "..", "..", "bin", "k8s", fmt.Sprintf("%s-%s-%s", k8sVersion, runtime.GOOS, runtime.GOARCH)), @@ -109,6 +112,8 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) err = routev1.Install(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) + err = gwapiv1.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) Expect(err).NotTo(HaveOccurred()) diff --git a/controllers/controller/devworkspacerouting/sync_httproutes.go b/controllers/controller/devworkspacerouting/sync_httproutes.go new file mode 100644 index 000000000..1ae360622 --- /dev/null +++ b/controllers/controller/devworkspacerouting/sync_httproutes.go @@ -0,0 +1,109 @@ +// +// Copyright (c) 2019-2026 Red Hat, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package devworkspacerouting + +import ( + "context" + "fmt" + + "github.com/devfile/devworkspace-operator/pkg/constants" + "github.com/devfile/devworkspace-operator/pkg/provision/sync" + + "k8s.io/apimachinery/pkg/labels" + "sigs.k8s.io/controller-runtime/pkg/client" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" +) + +func (r *DevWorkspaceRoutingReconciler) syncHTTPRoutes(routing *controllerv1alpha1.DevWorkspaceRouting, specHTTPRoutes []gwapiv1.HTTPRoute) (ok bool, clusterHTTPRoutes []gwapiv1.HTTPRoute, err error) { + httpRoutesInSync := true + + clusterHTTPRoutes, err = r.getClusterHTTPRoutes(routing) + if err != nil { + return false, nil, err + } + + toDelete := getHTTPRoutesToDelete(clusterHTTPRoutes, specHTTPRoutes) + for _, httpRoute := range toDelete { + err := r.Delete(context.TODO(), &httpRoute) + if err != nil { + return false, nil, err + } + httpRoutesInSync = false + } + + clusterAPI := sync.ClusterAPI{ + Client: r.Client, + Scheme: r.Scheme, + Logger: r.Log.WithValues("Request.Namespace", routing.Namespace, "Request.Name", routing.Name), + Ctx: context.TODO(), + } + + var updatedClusterHTTPRoutes []gwapiv1.HTTPRoute + for _, specHTTPRoute := range specHTTPRoutes { + clusterObj, err := sync.SyncObjectWithCluster(&specHTTPRoute, clusterAPI) + switch t := err.(type) { + case nil: + break + case *sync.NotInSyncError: + httpRoutesInSync = false + continue + case *sync.UnrecoverableSyncError: + return false, nil, t + default: + return false, nil, err + } + updatedClusterHTTPRoutes = append(updatedClusterHTTPRoutes, *clusterObj.(*gwapiv1.HTTPRoute)) + } + + return httpRoutesInSync, updatedClusterHTTPRoutes, nil +} + +func (r *DevWorkspaceRoutingReconciler) getClusterHTTPRoutes(routing *controllerv1alpha1.DevWorkspaceRouting) ([]gwapiv1.HTTPRoute, error) { + found := &gwapiv1.HTTPRouteList{} + labelSelector, err := labels.Parse(fmt.Sprintf("%s=%s", constants.DevWorkspaceIDLabel, routing.Spec.DevWorkspaceId)) + if err != nil { + return nil, err + } + listOptions := &client.ListOptions{ + Namespace: routing.Namespace, + LabelSelector: labelSelector, + } + err = r.List(context.TODO(), found, listOptions) + if err != nil { + return nil, err + } + return found.Items, nil +} + +func getHTTPRoutesToDelete(clusterHTTPRoutes, specHTTPRoutes []gwapiv1.HTTPRoute) []gwapiv1.HTTPRoute { + var toDelete []gwapiv1.HTTPRoute + for _, clusterHTTPRoute := range clusterHTTPRoutes { + if contains, _ := listContainsHTTPRouteByName(clusterHTTPRoute, specHTTPRoutes); !contains { + toDelete = append(toDelete, clusterHTTPRoute) + } + } + return toDelete +} + +func listContainsHTTPRouteByName(query gwapiv1.HTTPRoute, list []gwapiv1.HTTPRoute) (exists bool, idx int) { + for idx, listHTTPRoute := range list { + if query.Name == listHTTPRoute.Name { + return true, idx + } + } + return false, -1 +} diff --git a/controllers/controller/devworkspacerouting/testdata/gateway.networking.k8s.io_httproutes.yaml b/controllers/controller/devworkspacerouting/testdata/gateway.networking.k8s.io_httproutes.yaml new file mode 100644 index 000000000..8c272c5d0 --- /dev/null +++ b/controllers/controller/devworkspacerouting/testdata/gateway.networking.k8s.io_httproutes.yaml @@ -0,0 +1,5528 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + api-approved.kubernetes.io: https://github.com/kubernetes-sigs/gateway-api/pull/3328 + gateway.networking.k8s.io/bundle-version: v1.2.1 + gateway.networking.k8s.io/channel: standard + creationTimestamp: null + name: httproutes.gateway.networking.k8s.io +spec: + group: gateway.networking.k8s.io + names: + categories: + - gateway-api + kind: HTTPRoute + listKind: HTTPRouteList + plural: httproutes + singular: httproute + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.hostnames + name: Hostnames + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: |- + HTTPRoute provides a way to route HTTP requests. This includes the capability + to match requests by hostname, path, header, or query param. Filters can be + used to specify additional processing steps. Backends specify where matching + requests should be routed. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: Spec defines the desired state of HTTPRoute. + properties: + hostnames: + description: |- + Hostnames defines a set of hostnames that should match against the HTTP Host + header to select a HTTPRoute used to process the request. Implementations + MUST ignore any port value specified in the HTTP Host header while + performing a match and (absent of any applicable header modification + configuration) MUST forward this header unmodified to the backend. + + Valid values for Hostnames are determined by RFC 1123 definition of a + hostname with 2 notable exceptions: + + 1. IPs are not allowed. + 2. A hostname may be prefixed with a wildcard label (`*.`). The wildcard + label must appear by itself as the first label. + + If a hostname is specified by both the Listener and HTTPRoute, there + must be at least one intersecting hostname for the HTTPRoute to be + attached to the Listener. For example: + + * A Listener with `test.example.com` as the hostname matches HTTPRoutes + that have either not specified any hostnames, or have specified at + least one of `test.example.com` or `*.example.com`. + * A Listener with `*.example.com` as the hostname matches HTTPRoutes + that have either not specified any hostnames or have specified at least + one hostname that matches the Listener hostname. For example, + `*.example.com`, `test.example.com`, and `foo.test.example.com` would + all match. On the other hand, `example.com` and `test.example.net` would + not match. + + Hostnames that are prefixed with a wildcard label (`*.`) are interpreted + as a suffix match. That means that a match for `*.example.com` would match + both `test.example.com`, and `foo.test.example.com`, but not `example.com`. + + If both the Listener and HTTPRoute have specified hostnames, any + HTTPRoute hostnames that do not match the Listener hostname MUST be + ignored. For example, if a Listener specified `*.example.com`, and the + HTTPRoute specified `test.example.com` and `test.example.net`, + `test.example.net` must not be considered for a match. + + If both the Listener and HTTPRoute have specified hostnames, and none + match with the criteria above, then the HTTPRoute is not accepted. The + implementation must raise an 'Accepted' Condition with a status of + `False` in the corresponding RouteParentStatus. + + In the event that multiple HTTPRoutes specify intersecting hostnames (e.g. + overlapping wildcard matching and exact matching hostnames), precedence must + be given to rules from the HTTPRoute with the largest number of: + + * Characters in a matching non-wildcard hostname. + * Characters in a matching hostname. + + If ties exist across multiple Routes, the matching precedence rules for + HTTPRouteMatches takes over. + + Support: Core + items: + description: |- + Hostname is the fully qualified domain name of a network host. This matches + the RFC 1123 definition of a hostname with 2 notable exceptions: + + 1. IPs are not allowed. + 2. A hostname may be prefixed with a wildcard label (`*.`). The wildcard + label must appear by itself as the first label. + + Hostname can be "precise" which is a domain name without the terminating + dot of a network host (e.g. "foo.example.com") or "wildcard", which is a + domain name prefixed with a single wildcard label (e.g. `*.example.com`). + + Note that as per RFC1035 and RFC1123, a *label* must consist of lower case + alphanumeric characters or '-', and must start and end with an alphanumeric + character. No other punctuation is allowed. + maxLength: 253 + minLength: 1 + pattern: ^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + maxItems: 16 + type: array + parentRefs: + description: |+ + ParentRefs references the resources (usually Gateways) that a Route wants + to be attached to. Note that the referenced parent resource needs to + allow this for the attachment to be complete. For Gateways, that means + the Gateway needs to allow attachment from Routes of this kind and + namespace. For Services, that means the Service must either be in the same + namespace for a "producer" route, or the mesh implementation must support + and allow "consumer" routes for the referenced Service. ReferenceGrant is + not applicable for governing ParentRefs to Services - it is not possible to + create a "producer" route for a Service in a different namespace from the + Route. + + There are two kinds of parent resources with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + This API may be extended in the future to support additional kinds of parent + resources. + + ParentRefs must be _distinct_. This means either that: + + * They select different objects. If this is the case, then parentRef + entries are distinct. In terms of fields, this means that the + multi-part key defined by `group`, `kind`, `namespace`, and `name` must + be unique across all parentRef entries in the Route. + * They do not select different objects, but for each optional field used, + each ParentRef that selects the same object must set the same set of + optional fields to different values. If one ParentRef sets a + combination of optional fields, all must set the same combination. + + Some examples: + + * If one ParentRef sets `sectionName`, all ParentRefs referencing the + same object must also set `sectionName`. + * If one ParentRef sets `port`, all ParentRefs referencing the same + object must also set `port`. + * If one ParentRef sets `sectionName` and `port`, all ParentRefs + referencing the same object must also set `sectionName` and `port`. + + It is possible to separately reference multiple distinct objects that may + be collapsed by an implementation. For example, some implementations may + choose to merge compatible Gateway Listeners together. If that is the + case, the list of routes attached to those resources should also be + merged. + + Note that for ParentRefs that cross namespace boundaries, there are specific + rules. Cross-namespace references are only valid if they are explicitly + allowed by something in the namespace they are referring to. For example, + Gateway has the AllowedRoutes field, and ReferenceGrant provides a + generic way to enable other kinds of cross-namespace reference. + + + + + + + items: + description: |- + ParentReference identifies an API object (usually a Gateway) that can be considered + a parent of this resource (usually a route). There are two kinds of parent resources + with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + This API may be extended in the future to support additional kinds of parent + resources. + + The API object must be valid in the cluster; the Group and Kind must + be registered in the cluster for this reference to be valid. + properties: + group: + default: gateway.networking.k8s.io + description: |- + Group is the group of the referent. + When unspecified, "gateway.networking.k8s.io" is inferred. + To set the core API group (such as for a "Service" kind referent), + Group must be explicitly set to "" (empty string). + + Support: Core + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Gateway + description: |- + Kind is kind of the referent. + + There are two kinds of parent resources with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + Support for other resources is Implementation-Specific. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + Name is the name of the referent. + + Support: Core + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the referent. When unspecified, this refers + to the local namespace of the Route. + + Note that there are specific rules for ParentRefs which cross namespace + boundaries. Cross-namespace references are only valid if they are explicitly + allowed by something in the namespace they are referring to. For example: + Gateway has the AllowedRoutes field, and ReferenceGrant provides a + generic way to enable any other kind of cross-namespace reference. + + + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port is the network port this Route targets. It can be interpreted + differently based on the type of parent resource. + + When the parent resource is a Gateway, this targets all listeners + listening on the specified port that also support this kind of Route(and + select this Route). It's not recommended to set `Port` unless the + networking behaviors specified in a Route must apply to a specific port + as opposed to a listener(s) whose port(s) may be changed. When both Port + and SectionName are specified, the name and port of the selected listener + must match both specified values. + + + + Implementations MAY choose to support other parent resources. + Implementations supporting other types of parent resources MUST clearly + document how/if Port is interpreted. + + For the purpose of status, an attachment is considered successful as + long as the parent resource accepts it partially. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment + from the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, + the Route MUST be considered detached from the Gateway. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + sectionName: + description: |- + SectionName is the name of a section within the target resource. In the + following resources, SectionName is interpreted as the following: + + * Gateway: Listener name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + * Service: Port name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + + Implementations MAY choose to support attaching Routes to other resources. + If that is the case, they MUST clearly document how SectionName is + interpreted. + + When unspecified (empty string), this will reference the entire resource. + For the purpose of status, an attachment is considered successful if at + least one section in the parent resource accepts it. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment from + the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, the + Route MUST be considered detached from the Gateway. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - name + type: object + maxItems: 32 + type: array + x-kubernetes-validations: + - message: sectionName must be specified when parentRefs includes + 2 or more references to the same parent + rule: 'self.all(p1, self.all(p2, p1.group == p2.group && p1.kind + == p2.kind && p1.name == p2.name && (((!has(p1.__namespace__) + || p1.__namespace__ == '''') && (!has(p2.__namespace__) || p2.__namespace__ + == '''')) || (has(p1.__namespace__) && has(p2.__namespace__) && + p1.__namespace__ == p2.__namespace__ )) ? ((!has(p1.sectionName) + || p1.sectionName == '''') == (!has(p2.sectionName) || p2.sectionName + == '''')) : true))' + - message: sectionName must be unique when parentRefs includes 2 or + more references to the same parent + rule: self.all(p1, self.exists_one(p2, p1.group == p2.group && p1.kind + == p2.kind && p1.name == p2.name && (((!has(p1.__namespace__) + || p1.__namespace__ == '') && (!has(p2.__namespace__) || p2.__namespace__ + == '')) || (has(p1.__namespace__) && has(p2.__namespace__) && + p1.__namespace__ == p2.__namespace__ )) && (((!has(p1.sectionName) + || p1.sectionName == '') && (!has(p2.sectionName) || p2.sectionName + == '')) || (has(p1.sectionName) && has(p2.sectionName) && p1.sectionName + == p2.sectionName)))) + rules: + default: + - matches: + - path: + type: PathPrefix + value: / + description: |+ + Rules are a list of HTTP matchers, filters and actions. + + items: + description: |- + HTTPRouteRule defines semantics for matching an HTTP request based on + conditions (matches), processing it (filters), and forwarding the request to + an API object (backendRefs). + properties: + backendRefs: + description: |- + BackendRefs defines the backend(s) where matching requests should be + sent. + + Failure behavior here depends on how many BackendRefs are specified and + how many are invalid. + + If *all* entries in BackendRefs are invalid, and there are also no filters + specified in this route rule, *all* traffic which matches this rule MUST + receive a 500 status code. + + See the HTTPBackendRef definition for the rules about what makes a single + HTTPBackendRef invalid. + + When a HTTPBackendRef is invalid, 500 status codes MUST be returned for + requests that would have otherwise been routed to an invalid backend. If + multiple backends are specified, and some are invalid, the proportion of + requests that would otherwise have been routed to an invalid backend + MUST receive a 500 status code. + + For example, if two backends are specified with equal weights, and one is + invalid, 50 percent of traffic must receive a 500. Implementations may + choose how that 50 percent is determined. + + When a HTTPBackendRef refers to a Service that has no ready endpoints, + implementations SHOULD return a 503 for requests to that backend instead. + If an implementation chooses to do this, all of the above rules for 500 responses + MUST also apply for responses that return a 503. + + Support: Core for Kubernetes Service + + Support: Extended for Kubernetes ServiceImport + + Support: Implementation-specific for any other resource + + Support for weight: Core + items: + description: |- + HTTPBackendRef defines how a HTTPRoute forwards a HTTP request. + + Note that when a namespace different than the local namespace is specified, a + ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + + + When the BackendRef points to a Kubernetes Service, implementations SHOULD + honor the appProtocol field if it is set for the target Service Port. + + Implementations supporting appProtocol SHOULD recognize the Kubernetes + Standard Application Protocols defined in KEP-3726. + + If a Service appProtocol isn't specified, an implementation MAY infer the + backend protocol through its own means. Implementations MAY infer the + protocol from the Route type referring to the backend Service. + + If a Route is not able to send traffic to the backend using the specified + protocol then the backend is considered invalid. Implementations MUST set the + "ResolvedRefs" condition to "False" with the "UnsupportedProtocol" reason. + + + properties: + filters: + description: |- + Filters defined at this level should be executed if and only if the + request is being forwarded to the backend defined here. + + Support: Implementation-specific (For broader support of filters, use the + Filters field in HTTPRouteRule.) + items: + description: |- + HTTPRouteFilter defines processing steps that must be completed during the + request or response lifecycle. HTTPRouteFilters are meant as an extension + point to express processing that may be done in Gateway implementations. Some + examples include request or response modification, implementing + authentication strategies, rate-limiting, and traffic shaping. API + guarantee/conformance is defined based on the type of the filter. + properties: + extensionRef: + description: |- + ExtensionRef is an optional, implementation-specific extension to the + "filter" behavior. For example, resource "myroutefilter" in group + "networking.example.net"). ExtensionRef MUST NOT be used for core and + extended filters. + + This filter can be used multiple times within the same rule. + + Support: Implementation-specific + properties: + group: + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: Kind is kind of the referent. For + example "HTTPRoute" or "Service". + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + required: + - group + - kind + - name + type: object + requestHeaderModifier: + description: |- + RequestHeaderModifier defines a schema for a filter that modifies request + headers. + + Support: Core + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + requestMirror: + description: |+ + RequestMirror defines a schema for a filter that mirrors requests. + Requests are sent to the specified destination, but responses from + that destination are ignored. + + This filter can be used multiple times within the same rule. Note that + not all implementations will be able to support mirroring to multiple + backends. + + Support: Extended + + properties: + backendRef: + description: |- + BackendRef references a resource where mirrored requests are sent. + + Mirrored requests must be sent only to a single destination endpoint + within this BackendRef, irrespective of how many endpoints are present + within this BackendRef. + + If the referent cannot be found, this BackendRef is invalid and must be + dropped from the Gateway. The controller must ensure the "ResolvedRefs" + condition on the Route status is set to `status: False` and not configure + this backend in the underlying implementation. + + If there is a cross-namespace reference to an *existing* object + that is not allowed by a ReferenceGrant, the controller must ensure the + "ResolvedRefs" condition on the Route is set to `status: False`, + with the "RefNotPermitted" reason and not configure this backend in the + underlying implementation. + + In either error case, the Message of the `ResolvedRefs` Condition + should be used to provide more detail about the problem. + + Support: Extended for Kubernetes Service + + Support: Implementation-specific for any other resource + properties: + group: + default: "" + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Service + description: |- + Kind is the Kubernetes resource kind of the referent. For example + "Service". + + Defaults to "Service" when not specified. + + ExternalName services can refer to CNAME DNS records that may live + outside of the cluster and as such are difficult to reason about in + terms of conformance. They also may not be safe to forward to (see + CVE-2021-25740 for more information). Implementations SHOULD NOT + support ExternalName Services. + + Support: Core (Services with a type other than ExternalName) + + Support: Implementation-specific (Services with type ExternalName) + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the backend. When unspecified, the local + namespace is inferred. + + Note that when a namespace different than the local namespace is specified, + a ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port specifies the destination port number to use for this resource. + Port is required when the referent is a Kubernetes Service. In this + case, the port number is the service port number, not the target port. + For other resources, destination port might be derived from the referent + resource or this field. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + required: + - name + type: object + x-kubernetes-validations: + - message: Must have port for Service reference + rule: '(size(self.group) == 0 && self.kind + == ''Service'') ? has(self.port) : true' + required: + - backendRef + type: object + requestRedirect: + description: |- + RequestRedirect defines a schema for a filter that responds to the + request with an HTTP redirection. + + Support: Core + properties: + hostname: + description: |- + Hostname is the hostname to be used in the value of the `Location` + header in the response. + When empty, the hostname in the `Host` header of the request is used. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines parameters used to modify the path of the incoming request. + The modified path is then used to construct the `Location` header. When + empty, the request path is used as-is. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified + when type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? + has(self.replaceFullPath) : true' + - message: type must be 'ReplaceFullPath' when + replaceFullPath is set + rule: 'has(self.replaceFullPath) ? self.type + == ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified + when type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' + ? has(self.replacePrefixMatch) : true' + - message: type must be 'ReplacePrefixMatch' + when replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + port: + description: |- + Port is the port to be used in the value of the `Location` + header in the response. + + If no port is specified, the redirect port MUST be derived using the + following rules: + + * If redirect scheme is not-empty, the redirect port MUST be the well-known + port associated with the redirect scheme. Specifically "http" to port 80 + and "https" to port 443. If the redirect scheme does not have a + well-known port, the listener port of the Gateway SHOULD be used. + * If redirect scheme is empty, the redirect port MUST be the Gateway + Listener port. + + Implementations SHOULD NOT add the port number in the 'Location' + header in the following cases: + + * A Location header that will use HTTP (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 80. + * A Location header that will use HTTPS (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 443. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + scheme: + description: |- + Scheme is the scheme to be used in the value of the `Location` header in + the response. When empty, the scheme of the request is used. + + Scheme redirects can affect the port of the redirect, for more information, + refer to the documentation for the port field of this filter. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Extended + enum: + - http + - https + type: string + statusCode: + default: 302 + description: |- + StatusCode is the HTTP status code to be used in response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Core + enum: + - 301 + - 302 + type: integer + type: object + responseHeaderModifier: + description: |- + ResponseHeaderModifier defines a schema for a filter that modifies response + headers. + + Support: Extended + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + type: + description: |- + Type identifies the type of filter to apply. As with other API fields, + types are classified into three conformance levels: + + - Core: Filter types and their corresponding configuration defined by + "Support: Core" in this package, e.g. "RequestHeaderModifier". All + implementations must support core filters. + + - Extended: Filter types and their corresponding configuration defined by + "Support: Extended" in this package, e.g. "RequestMirror". Implementers + are encouraged to support extended filters. + + - Implementation-specific: Filters that are defined and supported by + specific vendors. + In the future, filters showing convergence in behavior across multiple + implementations will be considered for inclusion in extended or core + conformance levels. Filter-specific configuration for such filters + is specified using the ExtensionRef field. `Type` should be set to + "ExtensionRef" for custom filters. + + Implementers are encouraged to define custom implementation types to + extend the core API with implementation-specific behavior. + + If a reference to a custom filter type cannot be resolved, the filter + MUST NOT be skipped. Instead, requests that would have been processed by + that filter MUST receive a HTTP error response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - RequestHeaderModifier + - ResponseHeaderModifier + - RequestMirror + - RequestRedirect + - URLRewrite + - ExtensionRef + type: string + urlRewrite: + description: |- + URLRewrite defines a schema for a filter that modifies a request during forwarding. + + Support: Extended + properties: + hostname: + description: |- + Hostname is the value to be used to replace the Host header value during + forwarding. + + Support: Extended + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines a path rewrite. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified + when type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? + has(self.replaceFullPath) : true' + - message: type must be 'ReplaceFullPath' when + replaceFullPath is set + rule: 'has(self.replaceFullPath) ? self.type + == ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified + when type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' + ? has(self.replacePrefixMatch) : true' + - message: type must be 'ReplacePrefixMatch' + when replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + type: object + required: + - type + type: object + x-kubernetes-validations: + - message: filter.requestHeaderModifier must be nil + if the filter.type is not RequestHeaderModifier + rule: '!(has(self.requestHeaderModifier) && self.type + != ''RequestHeaderModifier'')' + - message: filter.requestHeaderModifier must be specified + for RequestHeaderModifier filter.type + rule: '!(!has(self.requestHeaderModifier) && self.type + == ''RequestHeaderModifier'')' + - message: filter.responseHeaderModifier must be nil + if the filter.type is not ResponseHeaderModifier + rule: '!(has(self.responseHeaderModifier) && self.type + != ''ResponseHeaderModifier'')' + - message: filter.responseHeaderModifier must be specified + for ResponseHeaderModifier filter.type + rule: '!(!has(self.responseHeaderModifier) && self.type + == ''ResponseHeaderModifier'')' + - message: filter.requestMirror must be nil if the filter.type + is not RequestMirror + rule: '!(has(self.requestMirror) && self.type != ''RequestMirror'')' + - message: filter.requestMirror must be specified for + RequestMirror filter.type + rule: '!(!has(self.requestMirror) && self.type == + ''RequestMirror'')' + - message: filter.requestRedirect must be nil if the + filter.type is not RequestRedirect + rule: '!(has(self.requestRedirect) && self.type != + ''RequestRedirect'')' + - message: filter.requestRedirect must be specified + for RequestRedirect filter.type + rule: '!(!has(self.requestRedirect) && self.type == + ''RequestRedirect'')' + - message: filter.urlRewrite must be nil if the filter.type + is not URLRewrite + rule: '!(has(self.urlRewrite) && self.type != ''URLRewrite'')' + - message: filter.urlRewrite must be specified for URLRewrite + filter.type + rule: '!(!has(self.urlRewrite) && self.type == ''URLRewrite'')' + - message: filter.extensionRef must be nil if the filter.type + is not ExtensionRef + rule: '!(has(self.extensionRef) && self.type != ''ExtensionRef'')' + - message: filter.extensionRef must be specified for + ExtensionRef filter.type + rule: '!(!has(self.extensionRef) && self.type == ''ExtensionRef'')' + maxItems: 16 + type: array + x-kubernetes-validations: + - message: May specify either httpRouteFilterRequestRedirect + or httpRouteFilterRequestRewrite, but not both + rule: '!(self.exists(f, f.type == ''RequestRedirect'') + && self.exists(f, f.type == ''URLRewrite''))' + - message: May specify either httpRouteFilterRequestRedirect + or httpRouteFilterRequestRewrite, but not both + rule: '!(self.exists(f, f.type == ''RequestRedirect'') + && self.exists(f, f.type == ''URLRewrite''))' + - message: RequestHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'RequestHeaderModifier').size() + <= 1 + - message: ResponseHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'ResponseHeaderModifier').size() + <= 1 + - message: RequestRedirect filter cannot be repeated + rule: self.filter(f, f.type == 'RequestRedirect').size() + <= 1 + - message: URLRewrite filter cannot be repeated + rule: self.filter(f, f.type == 'URLRewrite').size() + <= 1 + group: + default: "" + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Service + description: |- + Kind is the Kubernetes resource kind of the referent. For example + "Service". + + Defaults to "Service" when not specified. + + ExternalName services can refer to CNAME DNS records that may live + outside of the cluster and as such are difficult to reason about in + terms of conformance. They also may not be safe to forward to (see + CVE-2021-25740 for more information). Implementations SHOULD NOT + support ExternalName Services. + + Support: Core (Services with a type other than ExternalName) + + Support: Implementation-specific (Services with type ExternalName) + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the backend. When unspecified, the local + namespace is inferred. + + Note that when a namespace different than the local namespace is specified, + a ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port specifies the destination port number to use for this resource. + Port is required when the referent is a Kubernetes Service. In this + case, the port number is the service port number, not the target port. + For other resources, destination port might be derived from the referent + resource or this field. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + weight: + default: 1 + description: |- + Weight specifies the proportion of requests forwarded to the referenced + backend. This is computed as weight/(sum of all weights in this + BackendRefs list). For non-zero values, there may be some epsilon from + the exact proportion defined here depending on the precision an + implementation supports. Weight is not a percentage and the sum of + weights does not need to equal 100. + + If only one backend is specified and it has a weight greater than 0, 100% + of the traffic is forwarded to that backend. If weight is set to 0, no + traffic should be forwarded for this entry. If unspecified, weight + defaults to 1. + + Support for this field varies based on the context where used. + format: int32 + maximum: 1000000 + minimum: 0 + type: integer + required: + - name + type: object + x-kubernetes-validations: + - message: Must have port for Service reference + rule: '(size(self.group) == 0 && self.kind == ''Service'') + ? has(self.port) : true' + maxItems: 16 + type: array + filters: + description: |- + Filters define the filters that are applied to requests that match + this rule. + + Wherever possible, implementations SHOULD implement filters in the order + they are specified. + + Implementations MAY choose to implement this ordering strictly, rejecting + any combination or order of filters that can not be supported. If implementations + choose a strict interpretation of filter ordering, they MUST clearly document + that behavior. + + To reject an invalid combination or order of filters, implementations SHOULD + consider the Route Rules with this configuration invalid. If all Route Rules + in a Route are invalid, the entire Route would be considered invalid. If only + a portion of Route Rules are invalid, implementations MUST set the + "PartiallyInvalid" condition for the Route. + + Conformance-levels at this level are defined based on the type of filter: + + - ALL core filters MUST be supported by all implementations. + - Implementers are encouraged to support extended filters. + - Implementation-specific custom filters have no API guarantees across + implementations. + + Specifying the same filter multiple times is not supported unless explicitly + indicated in the filter. + + All filters are expected to be compatible with each other except for the + URLRewrite and RequestRedirect filters, which may not be combined. If an + implementation can not support other combinations of filters, they must clearly + document that limitation. In cases where incompatible or unsupported + filters are specified and cause the `Accepted` condition to be set to status + `False`, implementations may use the `IncompatibleFilters` reason to specify + this configuration error. + + Support: Core + items: + description: |- + HTTPRouteFilter defines processing steps that must be completed during the + request or response lifecycle. HTTPRouteFilters are meant as an extension + point to express processing that may be done in Gateway implementations. Some + examples include request or response modification, implementing + authentication strategies, rate-limiting, and traffic shaping. API + guarantee/conformance is defined based on the type of the filter. + properties: + extensionRef: + description: |- + ExtensionRef is an optional, implementation-specific extension to the + "filter" behavior. For example, resource "myroutefilter" in group + "networking.example.net"). ExtensionRef MUST NOT be used for core and + extended filters. + + This filter can be used multiple times within the same rule. + + Support: Implementation-specific + properties: + group: + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: Kind is kind of the referent. For example + "HTTPRoute" or "Service". + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + required: + - group + - kind + - name + type: object + requestHeaderModifier: + description: |- + RequestHeaderModifier defines a schema for a filter that modifies request + headers. + + Support: Core + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + requestMirror: + description: |+ + RequestMirror defines a schema for a filter that mirrors requests. + Requests are sent to the specified destination, but responses from + that destination are ignored. + + This filter can be used multiple times within the same rule. Note that + not all implementations will be able to support mirroring to multiple + backends. + + Support: Extended + + properties: + backendRef: + description: |- + BackendRef references a resource where mirrored requests are sent. + + Mirrored requests must be sent only to a single destination endpoint + within this BackendRef, irrespective of how many endpoints are present + within this BackendRef. + + If the referent cannot be found, this BackendRef is invalid and must be + dropped from the Gateway. The controller must ensure the "ResolvedRefs" + condition on the Route status is set to `status: False` and not configure + this backend in the underlying implementation. + + If there is a cross-namespace reference to an *existing* object + that is not allowed by a ReferenceGrant, the controller must ensure the + "ResolvedRefs" condition on the Route is set to `status: False`, + with the "RefNotPermitted" reason and not configure this backend in the + underlying implementation. + + In either error case, the Message of the `ResolvedRefs` Condition + should be used to provide more detail about the problem. + + Support: Extended for Kubernetes Service + + Support: Implementation-specific for any other resource + properties: + group: + default: "" + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Service + description: |- + Kind is the Kubernetes resource kind of the referent. For example + "Service". + + Defaults to "Service" when not specified. + + ExternalName services can refer to CNAME DNS records that may live + outside of the cluster and as such are difficult to reason about in + terms of conformance. They also may not be safe to forward to (see + CVE-2021-25740 for more information). Implementations SHOULD NOT + support ExternalName Services. + + Support: Core (Services with a type other than ExternalName) + + Support: Implementation-specific (Services with type ExternalName) + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the backend. When unspecified, the local + namespace is inferred. + + Note that when a namespace different than the local namespace is specified, + a ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port specifies the destination port number to use for this resource. + Port is required when the referent is a Kubernetes Service. In this + case, the port number is the service port number, not the target port. + For other resources, destination port might be derived from the referent + resource or this field. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + required: + - name + type: object + x-kubernetes-validations: + - message: Must have port for Service reference + rule: '(size(self.group) == 0 && self.kind == ''Service'') + ? has(self.port) : true' + required: + - backendRef + type: object + requestRedirect: + description: |- + RequestRedirect defines a schema for a filter that responds to the + request with an HTTP redirection. + + Support: Core + properties: + hostname: + description: |- + Hostname is the hostname to be used in the value of the `Location` + header in the response. + When empty, the hostname in the `Host` header of the request is used. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines parameters used to modify the path of the incoming request. + The modified path is then used to construct the `Location` header. When + empty, the request path is used as-is. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified when + type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? has(self.replaceFullPath) + : true' + - message: type must be 'ReplaceFullPath' when replaceFullPath + is set + rule: 'has(self.replaceFullPath) ? self.type == + ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified when + type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' ? has(self.replacePrefixMatch) + : true' + - message: type must be 'ReplacePrefixMatch' when + replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + port: + description: |- + Port is the port to be used in the value of the `Location` + header in the response. + + If no port is specified, the redirect port MUST be derived using the + following rules: + + * If redirect scheme is not-empty, the redirect port MUST be the well-known + port associated with the redirect scheme. Specifically "http" to port 80 + and "https" to port 443. If the redirect scheme does not have a + well-known port, the listener port of the Gateway SHOULD be used. + * If redirect scheme is empty, the redirect port MUST be the Gateway + Listener port. + + Implementations SHOULD NOT add the port number in the 'Location' + header in the following cases: + + * A Location header that will use HTTP (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 80. + * A Location header that will use HTTPS (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 443. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + scheme: + description: |- + Scheme is the scheme to be used in the value of the `Location` header in + the response. When empty, the scheme of the request is used. + + Scheme redirects can affect the port of the redirect, for more information, + refer to the documentation for the port field of this filter. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Extended + enum: + - http + - https + type: string + statusCode: + default: 302 + description: |- + StatusCode is the HTTP status code to be used in response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Core + enum: + - 301 + - 302 + type: integer + type: object + responseHeaderModifier: + description: |- + ResponseHeaderModifier defines a schema for a filter that modifies response + headers. + + Support: Extended + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + type: + description: |- + Type identifies the type of filter to apply. As with other API fields, + types are classified into three conformance levels: + + - Core: Filter types and their corresponding configuration defined by + "Support: Core" in this package, e.g. "RequestHeaderModifier". All + implementations must support core filters. + + - Extended: Filter types and their corresponding configuration defined by + "Support: Extended" in this package, e.g. "RequestMirror". Implementers + are encouraged to support extended filters. + + - Implementation-specific: Filters that are defined and supported by + specific vendors. + In the future, filters showing convergence in behavior across multiple + implementations will be considered for inclusion in extended or core + conformance levels. Filter-specific configuration for such filters + is specified using the ExtensionRef field. `Type` should be set to + "ExtensionRef" for custom filters. + + Implementers are encouraged to define custom implementation types to + extend the core API with implementation-specific behavior. + + If a reference to a custom filter type cannot be resolved, the filter + MUST NOT be skipped. Instead, requests that would have been processed by + that filter MUST receive a HTTP error response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - RequestHeaderModifier + - ResponseHeaderModifier + - RequestMirror + - RequestRedirect + - URLRewrite + - ExtensionRef + type: string + urlRewrite: + description: |- + URLRewrite defines a schema for a filter that modifies a request during forwarding. + + Support: Extended + properties: + hostname: + description: |- + Hostname is the value to be used to replace the Host header value during + forwarding. + + Support: Extended + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines a path rewrite. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified when + type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? has(self.replaceFullPath) + : true' + - message: type must be 'ReplaceFullPath' when replaceFullPath + is set + rule: 'has(self.replaceFullPath) ? self.type == + ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified when + type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' ? has(self.replacePrefixMatch) + : true' + - message: type must be 'ReplacePrefixMatch' when + replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + type: object + required: + - type + type: object + x-kubernetes-validations: + - message: filter.requestHeaderModifier must be nil if the + filter.type is not RequestHeaderModifier + rule: '!(has(self.requestHeaderModifier) && self.type != + ''RequestHeaderModifier'')' + - message: filter.requestHeaderModifier must be specified + for RequestHeaderModifier filter.type + rule: '!(!has(self.requestHeaderModifier) && self.type == + ''RequestHeaderModifier'')' + - message: filter.responseHeaderModifier must be nil if the + filter.type is not ResponseHeaderModifier + rule: '!(has(self.responseHeaderModifier) && self.type != + ''ResponseHeaderModifier'')' + - message: filter.responseHeaderModifier must be specified + for ResponseHeaderModifier filter.type + rule: '!(!has(self.responseHeaderModifier) && self.type + == ''ResponseHeaderModifier'')' + - message: filter.requestMirror must be nil if the filter.type + is not RequestMirror + rule: '!(has(self.requestMirror) && self.type != ''RequestMirror'')' + - message: filter.requestMirror must be specified for RequestMirror + filter.type + rule: '!(!has(self.requestMirror) && self.type == ''RequestMirror'')' + - message: filter.requestRedirect must be nil if the filter.type + is not RequestRedirect + rule: '!(has(self.requestRedirect) && self.type != ''RequestRedirect'')' + - message: filter.requestRedirect must be specified for RequestRedirect + filter.type + rule: '!(!has(self.requestRedirect) && self.type == ''RequestRedirect'')' + - message: filter.urlRewrite must be nil if the filter.type + is not URLRewrite + rule: '!(has(self.urlRewrite) && self.type != ''URLRewrite'')' + - message: filter.urlRewrite must be specified for URLRewrite + filter.type + rule: '!(!has(self.urlRewrite) && self.type == ''URLRewrite'')' + - message: filter.extensionRef must be nil if the filter.type + is not ExtensionRef + rule: '!(has(self.extensionRef) && self.type != ''ExtensionRef'')' + - message: filter.extensionRef must be specified for ExtensionRef + filter.type + rule: '!(!has(self.extensionRef) && self.type == ''ExtensionRef'')' + maxItems: 16 + type: array + x-kubernetes-validations: + - message: May specify either httpRouteFilterRequestRedirect + or httpRouteFilterRequestRewrite, but not both + rule: '!(self.exists(f, f.type == ''RequestRedirect'') && + self.exists(f, f.type == ''URLRewrite''))' + - message: RequestHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'RequestHeaderModifier').size() + <= 1 + - message: ResponseHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'ResponseHeaderModifier').size() + <= 1 + - message: RequestRedirect filter cannot be repeated + rule: self.filter(f, f.type == 'RequestRedirect').size() <= + 1 + - message: URLRewrite filter cannot be repeated + rule: self.filter(f, f.type == 'URLRewrite').size() <= 1 + matches: + default: + - path: + type: PathPrefix + value: / + description: |- + Matches define conditions used for matching the rule against incoming + HTTP requests. Each match is independent, i.e. this rule will be matched + if **any** one of the matches is satisfied. + + For example, take the following matches configuration: + + ``` + matches: + - path: + value: "/foo" + headers: + - name: "version" + value: "v2" + - path: + value: "/v2/foo" + ``` + + For a request to match against this rule, a request must satisfy + EITHER of the two conditions: + + - path prefixed with `/foo` AND contains the header `version: v2` + - path prefix of `/v2/foo` + + See the documentation for HTTPRouteMatch on how to specify multiple + match conditions that should be ANDed together. + + If no matches are specified, the default is a prefix + path match on "/", which has the effect of matching every + HTTP request. + + Proxy or Load Balancer routing configuration generated from HTTPRoutes + MUST prioritize matches based on the following criteria, continuing on + ties. Across all rules specified on applicable Routes, precedence must be + given to the match having: + + * "Exact" path match. + * "Prefix" path match with largest number of characters. + * Method match. + * Largest number of header matches. + * Largest number of query param matches. + + Note: The precedence of RegularExpression path matches are implementation-specific. + + If ties still exist across multiple Routes, matching precedence MUST be + determined in order of the following criteria, continuing on ties: + + * The oldest Route based on creation timestamp. + * The Route appearing first in alphabetical order by + "{namespace}/{name}". + + If ties still exist within an HTTPRoute, matching precedence MUST be granted + to the FIRST matching rule (in list order) with a match meeting the above + criteria. + + When no rules matching a request have been successfully attached to the + parent a request is coming from, a HTTP 404 status code MUST be returned. + items: + description: "HTTPRouteMatch defines the predicate used to + match requests to a given\naction. Multiple match types + are ANDed together, i.e. the match will\nevaluate to true + only if all conditions are satisfied.\n\nFor example, the + match below will match a HTTP request only if its path\nstarts + with `/foo` AND it contains the `version: v1` header:\n\n```\nmatch:\n\n\tpath:\n\t + \ value: \"/foo\"\n\theaders:\n\t- name: \"version\"\n\t + \ value \"v1\"\n\n```" + properties: + headers: + description: |- + Headers specifies HTTP request header matchers. Multiple match values are + ANDed together, meaning, a request must match all the specified headers + to select the route. + items: + description: |- + HTTPHeaderMatch describes how to select a HTTP route by matching HTTP request + headers. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, only the first + entry with an equivalent name MUST be considered for a match. Subsequent + entries with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + + When a header is repeated in an HTTP request, it is + implementation-specific behavior as to how this is represented. + Generally, proxies should follow the guidance from the RFC: + https://www.rfc-editor.org/rfc/rfc7230.html#section-3.2.2 regarding + processing a repeated header, with special handling for "Set-Cookie". + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + type: + default: Exact + description: |- + Type specifies how to match against the value of the header. + + Support: Core (Exact) + + Support: Implementation-specific (RegularExpression) + + Since RegularExpression HeaderMatchType has implementation-specific + conformance, implementations can support POSIX, PCRE or any other dialects + of regular expressions. Please read the implementation's documentation to + determine the supported dialect. + enum: + - Exact + - RegularExpression + type: string + value: + description: Value is the value of HTTP Header to + be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + method: + description: |- + Method specifies HTTP method matcher. + When specified, this route will be matched only if the request has the + specified method. + + Support: Extended + enum: + - GET + - HEAD + - POST + - PUT + - DELETE + - CONNECT + - OPTIONS + - TRACE + - PATCH + type: string + path: + default: + type: PathPrefix + value: / + description: |- + Path specifies a HTTP request path matcher. If this field is not + specified, a default prefix match on the "/" path is provided. + properties: + type: + default: PathPrefix + description: |- + Type specifies how to match against the path Value. + + Support: Core (Exact, PathPrefix) + + Support: Implementation-specific (RegularExpression) + enum: + - Exact + - PathPrefix + - RegularExpression + type: string + value: + default: / + description: Value of the HTTP path to match against. + maxLength: 1024 + type: string + type: object + x-kubernetes-validations: + - message: value must be an absolute path and start with + '/' when type one of ['Exact', 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? self.value.startsWith(''/'') + : true' + - message: must not contain '//' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''//'') + : true' + - message: must not contain '/./' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''/./'') + : true' + - message: must not contain '/../' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''/../'') + : true' + - message: must not contain '%2f' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''%2f'') + : true' + - message: must not contain '%2F' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''%2F'') + : true' + - message: must not contain '#' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''#'') + : true' + - message: must not end with '/..' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.endsWith(''/..'') + : true' + - message: must not end with '/.' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.endsWith(''/.'') + : true' + - message: type must be one of ['Exact', 'PathPrefix', + 'RegularExpression'] + rule: self.type in ['Exact','PathPrefix'] || self.type + == 'RegularExpression' + - message: must only contain valid characters (matching + ^(?:[-A-Za-z0-9/._~!$&'()*+,;=:@]|[%][0-9a-fA-F]{2})+$) + for types ['Exact', 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? self.value.matches(r"""^(?:[-A-Za-z0-9/._~!$&''()*+,;=:@]|[%][0-9a-fA-F]{2})+$""") + : true' + queryParams: + description: |- + QueryParams specifies HTTP query parameter matchers. Multiple match + values are ANDed together, meaning, a request must match all the + specified query parameters to select the route. + + Support: Extended + items: + description: |- + HTTPQueryParamMatch describes how to select a HTTP route by matching HTTP + query parameters. + properties: + name: + description: |- + Name is the name of the HTTP query param to be matched. This must be an + exact string match. (See + https://tools.ietf.org/html/rfc7230#section-2.7.3). + + If multiple entries specify equivalent query param names, only the first + entry with an equivalent name MUST be considered for a match. Subsequent + entries with an equivalent query param name MUST be ignored. + + If a query param is repeated in an HTTP request, the behavior is + purposely left undefined, since different data planes have different + capabilities. However, it is *recommended* that implementations should + match against the first value of the param if the data plane supports it, + as this behavior is expected in other load balancing contexts outside of + the Gateway API. + + Users SHOULD NOT route traffic based on repeated query params to guard + themselves against potential differences in the implementations. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + type: + default: Exact + description: |- + Type specifies how to match against the value of the query parameter. + + Support: Extended (Exact) + + Support: Implementation-specific (RegularExpression) + + Since RegularExpression QueryParamMatchType has Implementation-specific + conformance, implementations can support POSIX, PCRE or any other + dialects of regular expressions. Please read the implementation's + documentation to determine the supported dialect. + enum: + - Exact + - RegularExpression + type: string + value: + description: Value is the value of HTTP query param + to be matched. + maxLength: 1024 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + maxItems: 64 + type: array + timeouts: + description: |- + Timeouts defines the timeouts that can be configured for an HTTP request. + + Support: Extended + properties: + backendRequest: + description: |- + BackendRequest specifies a timeout for an individual request from the gateway + to a backend. This covers the time from when the request first starts being + sent from the gateway to when the full response has been received from the backend. + + Setting a timeout to the zero duration (e.g. "0s") SHOULD disable the timeout + completely. Implementations that cannot completely disable the timeout MUST + instead interpret the zero duration as the longest possible value to which + the timeout can be set. + + An entire client HTTP transaction with a gateway, covered by the Request timeout, + may result in more than one call from the gateway to the destination backend, + for example, if automatic retries are supported. + + The value of BackendRequest must be a Gateway API Duration string as defined by + GEP-2257. When this field is unspecified, its behavior is implementation-specific; + when specified, the value of BackendRequest must be no more than the value of the + Request timeout (since the Request timeout encompasses the BackendRequest timeout). + + Support: Extended + pattern: ^([0-9]{1,5}(h|m|s|ms)){1,4}$ + type: string + request: + description: |- + Request specifies the maximum duration for a gateway to respond to an HTTP request. + If the gateway has not been able to respond before this deadline is met, the gateway + MUST return a timeout error. + + For example, setting the `rules.timeouts.request` field to the value `10s` in an + `HTTPRoute` will cause a timeout if a client request is taking longer than 10 seconds + to complete. + + Setting a timeout to the zero duration (e.g. "0s") SHOULD disable the timeout + completely. Implementations that cannot completely disable the timeout MUST + instead interpret the zero duration as the longest possible value to which + the timeout can be set. + + This timeout is intended to cover as close to the whole request-response transaction + as possible although an implementation MAY choose to start the timeout after the entire + request stream has been received instead of immediately after the transaction is + initiated by the client. + + The value of Request is a Gateway API Duration string as defined by GEP-2257. When this + field is unspecified, request timeout behavior is implementation-specific. + + Support: Extended + pattern: ^([0-9]{1,5}(h|m|s|ms)){1,4}$ + type: string + type: object + x-kubernetes-validations: + - message: backendRequest timeout cannot be longer than request + timeout + rule: '!(has(self.request) && has(self.backendRequest) && + duration(self.request) != duration(''0s'') && duration(self.backendRequest) + > duration(self.request))' + type: object + x-kubernetes-validations: + - message: RequestRedirect filter must not be used together with + backendRefs + rule: '(has(self.backendRefs) && size(self.backendRefs) > 0) ? + (!has(self.filters) || self.filters.all(f, !has(f.requestRedirect))): + true' + - message: When using RequestRedirect filter with path.replacePrefixMatch, + exactly one PathPrefix match must be specified + rule: '(has(self.filters) && self.filters.exists_one(f, has(f.requestRedirect) + && has(f.requestRedirect.path) && f.requestRedirect.path.type + == ''ReplacePrefixMatch'' && has(f.requestRedirect.path.replacePrefixMatch))) + ? ((size(self.matches) != 1 || !has(self.matches[0].path) || + self.matches[0].path.type != ''PathPrefix'') ? false : true) + : true' + - message: When using URLRewrite filter with path.replacePrefixMatch, + exactly one PathPrefix match must be specified + rule: '(has(self.filters) && self.filters.exists_one(f, has(f.urlRewrite) + && has(f.urlRewrite.path) && f.urlRewrite.path.type == ''ReplacePrefixMatch'' + && has(f.urlRewrite.path.replacePrefixMatch))) ? ((size(self.matches) + != 1 || !has(self.matches[0].path) || self.matches[0].path.type + != ''PathPrefix'') ? false : true) : true' + - message: Within backendRefs, when using RequestRedirect filter + with path.replacePrefixMatch, exactly one PathPrefix match must + be specified + rule: '(has(self.backendRefs) && self.backendRefs.exists_one(b, + (has(b.filters) && b.filters.exists_one(f, has(f.requestRedirect) + && has(f.requestRedirect.path) && f.requestRedirect.path.type + == ''ReplacePrefixMatch'' && has(f.requestRedirect.path.replacePrefixMatch))) + )) ? ((size(self.matches) != 1 || !has(self.matches[0].path) + || self.matches[0].path.type != ''PathPrefix'') ? false : true) + : true' + - message: Within backendRefs, When using URLRewrite filter with + path.replacePrefixMatch, exactly one PathPrefix match must be + specified + rule: '(has(self.backendRefs) && self.backendRefs.exists_one(b, + (has(b.filters) && b.filters.exists_one(f, has(f.urlRewrite) + && has(f.urlRewrite.path) && f.urlRewrite.path.type == ''ReplacePrefixMatch'' + && has(f.urlRewrite.path.replacePrefixMatch))) )) ? ((size(self.matches) + != 1 || !has(self.matches[0].path) || self.matches[0].path.type + != ''PathPrefix'') ? false : true) : true' + maxItems: 16 + type: array + x-kubernetes-validations: + - message: While 16 rules and 64 matches per rule are allowed, the + total number of matches across all rules in a route must be less + than 128 + rule: '(self.size() > 0 ? self[0].matches.size() : 0) + (self.size() + > 1 ? self[1].matches.size() : 0) + (self.size() > 2 ? self[2].matches.size() + : 0) + (self.size() > 3 ? self[3].matches.size() : 0) + (self.size() + > 4 ? self[4].matches.size() : 0) + (self.size() > 5 ? self[5].matches.size() + : 0) + (self.size() > 6 ? self[6].matches.size() : 0) + (self.size() + > 7 ? self[7].matches.size() : 0) + (self.size() > 8 ? self[8].matches.size() + : 0) + (self.size() > 9 ? self[9].matches.size() : 0) + (self.size() + > 10 ? self[10].matches.size() : 0) + (self.size() > 11 ? self[11].matches.size() + : 0) + (self.size() > 12 ? self[12].matches.size() : 0) + (self.size() + > 13 ? self[13].matches.size() : 0) + (self.size() > 14 ? self[14].matches.size() + : 0) + (self.size() > 15 ? self[15].matches.size() : 0) <= 128' + type: object + status: + description: Status defines the current state of HTTPRoute. + properties: + parents: + description: |- + Parents is a list of parent resources (usually Gateways) that are + associated with the route, and the status of the route with respect to + each parent. When this route attaches to a parent, the controller that + manages the parent must add an entry to this list when the controller + first sees the route and should update the entry as appropriate when the + route or gateway is modified. + + Note that parent references that cannot be resolved by an implementation + of this API will not be added to this list. Implementations of this API + can only populate Route status for the Gateways/parent resources they are + responsible for. + + A maximum of 32 Gateways will be represented in this list. An empty list + means the route has not been attached to any Gateway. + items: + description: |- + RouteParentStatus describes the status of a route with respect to an + associated Parent. + properties: + conditions: + description: |- + Conditions describes the status of the route with respect to the Gateway. + Note that the route's availability is also subject to the Gateway's own + status conditions and listener status. + + If the Route's ParentRef specifies an existing Gateway that supports + Routes of this kind AND that Gateway's controller has sufficient access, + then that Gateway's controller MUST set the "Accepted" condition on the + Route, to indicate whether the route has been accepted or rejected by the + Gateway, and why. + + A Route MUST be considered "Accepted" if at least one of the Route's + rules is implemented by the Gateway. + + There are a number of cases where the "Accepted" condition may not be set + due to lack of controller visibility, that includes when: + + * The Route refers to a non-existent parent. + * The Route is of a type that the controller does not support. + * The Route is in a namespace the controller does not have access to. + items: + description: Condition contains details for one aspect of + the current state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, + Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 8 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + controllerName: + description: |- + ControllerName is a domain/path string that indicates the name of the + controller that wrote this status. This corresponds with the + controllerName field on GatewayClass. + + Example: "example.net/gateway-controller". + + The format of this field is DOMAIN "/" PATH, where DOMAIN and PATH are + valid Kubernetes names + (https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names). + + Controllers MUST populate this field when writing status. Controllers should ensure that + entries to status populated with their ControllerName are cleaned up when they are no + longer necessary. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[A-Za-z0-9\/\-._~%!$&'()*+,;=:]+$ + type: string + parentRef: + description: |- + ParentRef corresponds with a ParentRef in the spec that this + RouteParentStatus struct describes the status of. + properties: + group: + default: gateway.networking.k8s.io + description: |- + Group is the group of the referent. + When unspecified, "gateway.networking.k8s.io" is inferred. + To set the core API group (such as for a "Service" kind referent), + Group must be explicitly set to "" (empty string). + + Support: Core + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Gateway + description: |- + Kind is kind of the referent. + + There are two kinds of parent resources with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + Support for other resources is Implementation-Specific. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + Name is the name of the referent. + + Support: Core + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the referent. When unspecified, this refers + to the local namespace of the Route. + + Note that there are specific rules for ParentRefs which cross namespace + boundaries. Cross-namespace references are only valid if they are explicitly + allowed by something in the namespace they are referring to. For example: + Gateway has the AllowedRoutes field, and ReferenceGrant provides a + generic way to enable any other kind of cross-namespace reference. + + + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port is the network port this Route targets. It can be interpreted + differently based on the type of parent resource. + + When the parent resource is a Gateway, this targets all listeners + listening on the specified port that also support this kind of Route(and + select this Route). It's not recommended to set `Port` unless the + networking behaviors specified in a Route must apply to a specific port + as opposed to a listener(s) whose port(s) may be changed. When both Port + and SectionName are specified, the name and port of the selected listener + must match both specified values. + + + + Implementations MAY choose to support other parent resources. + Implementations supporting other types of parent resources MUST clearly + document how/if Port is interpreted. + + For the purpose of status, an attachment is considered successful as + long as the parent resource accepts it partially. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment + from the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, + the Route MUST be considered detached from the Gateway. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + sectionName: + description: |- + SectionName is the name of a section within the target resource. In the + following resources, SectionName is interpreted as the following: + + * Gateway: Listener name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + * Service: Port name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + + Implementations MAY choose to support attaching Routes to other resources. + If that is the case, they MUST clearly document how SectionName is + interpreted. + + When unspecified (empty string), this will reference the entire resource. + For the purpose of status, an attachment is considered successful if at + least one section in the parent resource accepts it. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment from + the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, the + Route MUST be considered detached from the Gateway. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - name + type: object + required: + - controllerName + - parentRef + type: object + maxItems: 32 + type: array + required: + - parents + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} + - additionalPrinterColumns: + - jsonPath: .spec.hostnames + name: Hostnames + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1beta1 + schema: + openAPIV3Schema: + description: |- + HTTPRoute provides a way to route HTTP requests. This includes the capability + to match requests by hostname, path, header, or query param. Filters can be + used to specify additional processing steps. Backends specify where matching + requests should be routed. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: Spec defines the desired state of HTTPRoute. + properties: + hostnames: + description: |- + Hostnames defines a set of hostnames that should match against the HTTP Host + header to select a HTTPRoute used to process the request. Implementations + MUST ignore any port value specified in the HTTP Host header while + performing a match and (absent of any applicable header modification + configuration) MUST forward this header unmodified to the backend. + + Valid values for Hostnames are determined by RFC 1123 definition of a + hostname with 2 notable exceptions: + + 1. IPs are not allowed. + 2. A hostname may be prefixed with a wildcard label (`*.`). The wildcard + label must appear by itself as the first label. + + If a hostname is specified by both the Listener and HTTPRoute, there + must be at least one intersecting hostname for the HTTPRoute to be + attached to the Listener. For example: + + * A Listener with `test.example.com` as the hostname matches HTTPRoutes + that have either not specified any hostnames, or have specified at + least one of `test.example.com` or `*.example.com`. + * A Listener with `*.example.com` as the hostname matches HTTPRoutes + that have either not specified any hostnames or have specified at least + one hostname that matches the Listener hostname. For example, + `*.example.com`, `test.example.com`, and `foo.test.example.com` would + all match. On the other hand, `example.com` and `test.example.net` would + not match. + + Hostnames that are prefixed with a wildcard label (`*.`) are interpreted + as a suffix match. That means that a match for `*.example.com` would match + both `test.example.com`, and `foo.test.example.com`, but not `example.com`. + + If both the Listener and HTTPRoute have specified hostnames, any + HTTPRoute hostnames that do not match the Listener hostname MUST be + ignored. For example, if a Listener specified `*.example.com`, and the + HTTPRoute specified `test.example.com` and `test.example.net`, + `test.example.net` must not be considered for a match. + + If both the Listener and HTTPRoute have specified hostnames, and none + match with the criteria above, then the HTTPRoute is not accepted. The + implementation must raise an 'Accepted' Condition with a status of + `False` in the corresponding RouteParentStatus. + + In the event that multiple HTTPRoutes specify intersecting hostnames (e.g. + overlapping wildcard matching and exact matching hostnames), precedence must + be given to rules from the HTTPRoute with the largest number of: + + * Characters in a matching non-wildcard hostname. + * Characters in a matching hostname. + + If ties exist across multiple Routes, the matching precedence rules for + HTTPRouteMatches takes over. + + Support: Core + items: + description: |- + Hostname is the fully qualified domain name of a network host. This matches + the RFC 1123 definition of a hostname with 2 notable exceptions: + + 1. IPs are not allowed. + 2. A hostname may be prefixed with a wildcard label (`*.`). The wildcard + label must appear by itself as the first label. + + Hostname can be "precise" which is a domain name without the terminating + dot of a network host (e.g. "foo.example.com") or "wildcard", which is a + domain name prefixed with a single wildcard label (e.g. `*.example.com`). + + Note that as per RFC1035 and RFC1123, a *label* must consist of lower case + alphanumeric characters or '-', and must start and end with an alphanumeric + character. No other punctuation is allowed. + maxLength: 253 + minLength: 1 + pattern: ^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + maxItems: 16 + type: array + parentRefs: + description: |+ + ParentRefs references the resources (usually Gateways) that a Route wants + to be attached to. Note that the referenced parent resource needs to + allow this for the attachment to be complete. For Gateways, that means + the Gateway needs to allow attachment from Routes of this kind and + namespace. For Services, that means the Service must either be in the same + namespace for a "producer" route, or the mesh implementation must support + and allow "consumer" routes for the referenced Service. ReferenceGrant is + not applicable for governing ParentRefs to Services - it is not possible to + create a "producer" route for a Service in a different namespace from the + Route. + + There are two kinds of parent resources with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + This API may be extended in the future to support additional kinds of parent + resources. + + ParentRefs must be _distinct_. This means either that: + + * They select different objects. If this is the case, then parentRef + entries are distinct. In terms of fields, this means that the + multi-part key defined by `group`, `kind`, `namespace`, and `name` must + be unique across all parentRef entries in the Route. + * They do not select different objects, but for each optional field used, + each ParentRef that selects the same object must set the same set of + optional fields to different values. If one ParentRef sets a + combination of optional fields, all must set the same combination. + + Some examples: + + * If one ParentRef sets `sectionName`, all ParentRefs referencing the + same object must also set `sectionName`. + * If one ParentRef sets `port`, all ParentRefs referencing the same + object must also set `port`. + * If one ParentRef sets `sectionName` and `port`, all ParentRefs + referencing the same object must also set `sectionName` and `port`. + + It is possible to separately reference multiple distinct objects that may + be collapsed by an implementation. For example, some implementations may + choose to merge compatible Gateway Listeners together. If that is the + case, the list of routes attached to those resources should also be + merged. + + Note that for ParentRefs that cross namespace boundaries, there are specific + rules. Cross-namespace references are only valid if they are explicitly + allowed by something in the namespace they are referring to. For example, + Gateway has the AllowedRoutes field, and ReferenceGrant provides a + generic way to enable other kinds of cross-namespace reference. + + + + + + + items: + description: |- + ParentReference identifies an API object (usually a Gateway) that can be considered + a parent of this resource (usually a route). There are two kinds of parent resources + with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + This API may be extended in the future to support additional kinds of parent + resources. + + The API object must be valid in the cluster; the Group and Kind must + be registered in the cluster for this reference to be valid. + properties: + group: + default: gateway.networking.k8s.io + description: |- + Group is the group of the referent. + When unspecified, "gateway.networking.k8s.io" is inferred. + To set the core API group (such as for a "Service" kind referent), + Group must be explicitly set to "" (empty string). + + Support: Core + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Gateway + description: |- + Kind is kind of the referent. + + There are two kinds of parent resources with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + Support for other resources is Implementation-Specific. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + Name is the name of the referent. + + Support: Core + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the referent. When unspecified, this refers + to the local namespace of the Route. + + Note that there are specific rules for ParentRefs which cross namespace + boundaries. Cross-namespace references are only valid if they are explicitly + allowed by something in the namespace they are referring to. For example: + Gateway has the AllowedRoutes field, and ReferenceGrant provides a + generic way to enable any other kind of cross-namespace reference. + + + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port is the network port this Route targets. It can be interpreted + differently based on the type of parent resource. + + When the parent resource is a Gateway, this targets all listeners + listening on the specified port that also support this kind of Route(and + select this Route). It's not recommended to set `Port` unless the + networking behaviors specified in a Route must apply to a specific port + as opposed to a listener(s) whose port(s) may be changed. When both Port + and SectionName are specified, the name and port of the selected listener + must match both specified values. + + + + Implementations MAY choose to support other parent resources. + Implementations supporting other types of parent resources MUST clearly + document how/if Port is interpreted. + + For the purpose of status, an attachment is considered successful as + long as the parent resource accepts it partially. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment + from the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, + the Route MUST be considered detached from the Gateway. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + sectionName: + description: |- + SectionName is the name of a section within the target resource. In the + following resources, SectionName is interpreted as the following: + + * Gateway: Listener name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + * Service: Port name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + + Implementations MAY choose to support attaching Routes to other resources. + If that is the case, they MUST clearly document how SectionName is + interpreted. + + When unspecified (empty string), this will reference the entire resource. + For the purpose of status, an attachment is considered successful if at + least one section in the parent resource accepts it. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment from + the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, the + Route MUST be considered detached from the Gateway. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - name + type: object + maxItems: 32 + type: array + x-kubernetes-validations: + - message: sectionName must be specified when parentRefs includes + 2 or more references to the same parent + rule: 'self.all(p1, self.all(p2, p1.group == p2.group && p1.kind + == p2.kind && p1.name == p2.name && (((!has(p1.__namespace__) + || p1.__namespace__ == '''') && (!has(p2.__namespace__) || p2.__namespace__ + == '''')) || (has(p1.__namespace__) && has(p2.__namespace__) && + p1.__namespace__ == p2.__namespace__ )) ? ((!has(p1.sectionName) + || p1.sectionName == '''') == (!has(p2.sectionName) || p2.sectionName + == '''')) : true))' + - message: sectionName must be unique when parentRefs includes 2 or + more references to the same parent + rule: self.all(p1, self.exists_one(p2, p1.group == p2.group && p1.kind + == p2.kind && p1.name == p2.name && (((!has(p1.__namespace__) + || p1.__namespace__ == '') && (!has(p2.__namespace__) || p2.__namespace__ + == '')) || (has(p1.__namespace__) && has(p2.__namespace__) && + p1.__namespace__ == p2.__namespace__ )) && (((!has(p1.sectionName) + || p1.sectionName == '') && (!has(p2.sectionName) || p2.sectionName + == '')) || (has(p1.sectionName) && has(p2.sectionName) && p1.sectionName + == p2.sectionName)))) + rules: + default: + - matches: + - path: + type: PathPrefix + value: / + description: |+ + Rules are a list of HTTP matchers, filters and actions. + + items: + description: |- + HTTPRouteRule defines semantics for matching an HTTP request based on + conditions (matches), processing it (filters), and forwarding the request to + an API object (backendRefs). + properties: + backendRefs: + description: |- + BackendRefs defines the backend(s) where matching requests should be + sent. + + Failure behavior here depends on how many BackendRefs are specified and + how many are invalid. + + If *all* entries in BackendRefs are invalid, and there are also no filters + specified in this route rule, *all* traffic which matches this rule MUST + receive a 500 status code. + + See the HTTPBackendRef definition for the rules about what makes a single + HTTPBackendRef invalid. + + When a HTTPBackendRef is invalid, 500 status codes MUST be returned for + requests that would have otherwise been routed to an invalid backend. If + multiple backends are specified, and some are invalid, the proportion of + requests that would otherwise have been routed to an invalid backend + MUST receive a 500 status code. + + For example, if two backends are specified with equal weights, and one is + invalid, 50 percent of traffic must receive a 500. Implementations may + choose how that 50 percent is determined. + + When a HTTPBackendRef refers to a Service that has no ready endpoints, + implementations SHOULD return a 503 for requests to that backend instead. + If an implementation chooses to do this, all of the above rules for 500 responses + MUST also apply for responses that return a 503. + + Support: Core for Kubernetes Service + + Support: Extended for Kubernetes ServiceImport + + Support: Implementation-specific for any other resource + + Support for weight: Core + items: + description: |- + HTTPBackendRef defines how a HTTPRoute forwards a HTTP request. + + Note that when a namespace different than the local namespace is specified, a + ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + + + When the BackendRef points to a Kubernetes Service, implementations SHOULD + honor the appProtocol field if it is set for the target Service Port. + + Implementations supporting appProtocol SHOULD recognize the Kubernetes + Standard Application Protocols defined in KEP-3726. + + If a Service appProtocol isn't specified, an implementation MAY infer the + backend protocol through its own means. Implementations MAY infer the + protocol from the Route type referring to the backend Service. + + If a Route is not able to send traffic to the backend using the specified + protocol then the backend is considered invalid. Implementations MUST set the + "ResolvedRefs" condition to "False" with the "UnsupportedProtocol" reason. + + + properties: + filters: + description: |- + Filters defined at this level should be executed if and only if the + request is being forwarded to the backend defined here. + + Support: Implementation-specific (For broader support of filters, use the + Filters field in HTTPRouteRule.) + items: + description: |- + HTTPRouteFilter defines processing steps that must be completed during the + request or response lifecycle. HTTPRouteFilters are meant as an extension + point to express processing that may be done in Gateway implementations. Some + examples include request or response modification, implementing + authentication strategies, rate-limiting, and traffic shaping. API + guarantee/conformance is defined based on the type of the filter. + properties: + extensionRef: + description: |- + ExtensionRef is an optional, implementation-specific extension to the + "filter" behavior. For example, resource "myroutefilter" in group + "networking.example.net"). ExtensionRef MUST NOT be used for core and + extended filters. + + This filter can be used multiple times within the same rule. + + Support: Implementation-specific + properties: + group: + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: Kind is kind of the referent. For + example "HTTPRoute" or "Service". + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + required: + - group + - kind + - name + type: object + requestHeaderModifier: + description: |- + RequestHeaderModifier defines a schema for a filter that modifies request + headers. + + Support: Core + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + requestMirror: + description: |+ + RequestMirror defines a schema for a filter that mirrors requests. + Requests are sent to the specified destination, but responses from + that destination are ignored. + + This filter can be used multiple times within the same rule. Note that + not all implementations will be able to support mirroring to multiple + backends. + + Support: Extended + + properties: + backendRef: + description: |- + BackendRef references a resource where mirrored requests are sent. + + Mirrored requests must be sent only to a single destination endpoint + within this BackendRef, irrespective of how many endpoints are present + within this BackendRef. + + If the referent cannot be found, this BackendRef is invalid and must be + dropped from the Gateway. The controller must ensure the "ResolvedRefs" + condition on the Route status is set to `status: False` and not configure + this backend in the underlying implementation. + + If there is a cross-namespace reference to an *existing* object + that is not allowed by a ReferenceGrant, the controller must ensure the + "ResolvedRefs" condition on the Route is set to `status: False`, + with the "RefNotPermitted" reason and not configure this backend in the + underlying implementation. + + In either error case, the Message of the `ResolvedRefs` Condition + should be used to provide more detail about the problem. + + Support: Extended for Kubernetes Service + + Support: Implementation-specific for any other resource + properties: + group: + default: "" + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Service + description: |- + Kind is the Kubernetes resource kind of the referent. For example + "Service". + + Defaults to "Service" when not specified. + + ExternalName services can refer to CNAME DNS records that may live + outside of the cluster and as such are difficult to reason about in + terms of conformance. They also may not be safe to forward to (see + CVE-2021-25740 for more information). Implementations SHOULD NOT + support ExternalName Services. + + Support: Core (Services with a type other than ExternalName) + + Support: Implementation-specific (Services with type ExternalName) + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the backend. When unspecified, the local + namespace is inferred. + + Note that when a namespace different than the local namespace is specified, + a ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port specifies the destination port number to use for this resource. + Port is required when the referent is a Kubernetes Service. In this + case, the port number is the service port number, not the target port. + For other resources, destination port might be derived from the referent + resource or this field. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + required: + - name + type: object + x-kubernetes-validations: + - message: Must have port for Service reference + rule: '(size(self.group) == 0 && self.kind + == ''Service'') ? has(self.port) : true' + required: + - backendRef + type: object + requestRedirect: + description: |- + RequestRedirect defines a schema for a filter that responds to the + request with an HTTP redirection. + + Support: Core + properties: + hostname: + description: |- + Hostname is the hostname to be used in the value of the `Location` + header in the response. + When empty, the hostname in the `Host` header of the request is used. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines parameters used to modify the path of the incoming request. + The modified path is then used to construct the `Location` header. When + empty, the request path is used as-is. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified + when type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? + has(self.replaceFullPath) : true' + - message: type must be 'ReplaceFullPath' when + replaceFullPath is set + rule: 'has(self.replaceFullPath) ? self.type + == ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified + when type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' + ? has(self.replacePrefixMatch) : true' + - message: type must be 'ReplacePrefixMatch' + when replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + port: + description: |- + Port is the port to be used in the value of the `Location` + header in the response. + + If no port is specified, the redirect port MUST be derived using the + following rules: + + * If redirect scheme is not-empty, the redirect port MUST be the well-known + port associated with the redirect scheme. Specifically "http" to port 80 + and "https" to port 443. If the redirect scheme does not have a + well-known port, the listener port of the Gateway SHOULD be used. + * If redirect scheme is empty, the redirect port MUST be the Gateway + Listener port. + + Implementations SHOULD NOT add the port number in the 'Location' + header in the following cases: + + * A Location header that will use HTTP (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 80. + * A Location header that will use HTTPS (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 443. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + scheme: + description: |- + Scheme is the scheme to be used in the value of the `Location` header in + the response. When empty, the scheme of the request is used. + + Scheme redirects can affect the port of the redirect, for more information, + refer to the documentation for the port field of this filter. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Extended + enum: + - http + - https + type: string + statusCode: + default: 302 + description: |- + StatusCode is the HTTP status code to be used in response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Core + enum: + - 301 + - 302 + type: integer + type: object + responseHeaderModifier: + description: |- + ResponseHeaderModifier defines a schema for a filter that modifies response + headers. + + Support: Extended + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP + Header name and value as defined by RFC + 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP + Header to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + type: + description: |- + Type identifies the type of filter to apply. As with other API fields, + types are classified into three conformance levels: + + - Core: Filter types and their corresponding configuration defined by + "Support: Core" in this package, e.g. "RequestHeaderModifier". All + implementations must support core filters. + + - Extended: Filter types and their corresponding configuration defined by + "Support: Extended" in this package, e.g. "RequestMirror". Implementers + are encouraged to support extended filters. + + - Implementation-specific: Filters that are defined and supported by + specific vendors. + In the future, filters showing convergence in behavior across multiple + implementations will be considered for inclusion in extended or core + conformance levels. Filter-specific configuration for such filters + is specified using the ExtensionRef field. `Type` should be set to + "ExtensionRef" for custom filters. + + Implementers are encouraged to define custom implementation types to + extend the core API with implementation-specific behavior. + + If a reference to a custom filter type cannot be resolved, the filter + MUST NOT be skipped. Instead, requests that would have been processed by + that filter MUST receive a HTTP error response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - RequestHeaderModifier + - ResponseHeaderModifier + - RequestMirror + - RequestRedirect + - URLRewrite + - ExtensionRef + type: string + urlRewrite: + description: |- + URLRewrite defines a schema for a filter that modifies a request during forwarding. + + Support: Extended + properties: + hostname: + description: |- + Hostname is the value to be used to replace the Host header value during + forwarding. + + Support: Extended + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines a path rewrite. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified + when type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? + has(self.replaceFullPath) : true' + - message: type must be 'ReplaceFullPath' when + replaceFullPath is set + rule: 'has(self.replaceFullPath) ? self.type + == ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified + when type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' + ? has(self.replacePrefixMatch) : true' + - message: type must be 'ReplacePrefixMatch' + when replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + type: object + required: + - type + type: object + x-kubernetes-validations: + - message: filter.requestHeaderModifier must be nil + if the filter.type is not RequestHeaderModifier + rule: '!(has(self.requestHeaderModifier) && self.type + != ''RequestHeaderModifier'')' + - message: filter.requestHeaderModifier must be specified + for RequestHeaderModifier filter.type + rule: '!(!has(self.requestHeaderModifier) && self.type + == ''RequestHeaderModifier'')' + - message: filter.responseHeaderModifier must be nil + if the filter.type is not ResponseHeaderModifier + rule: '!(has(self.responseHeaderModifier) && self.type + != ''ResponseHeaderModifier'')' + - message: filter.responseHeaderModifier must be specified + for ResponseHeaderModifier filter.type + rule: '!(!has(self.responseHeaderModifier) && self.type + == ''ResponseHeaderModifier'')' + - message: filter.requestMirror must be nil if the filter.type + is not RequestMirror + rule: '!(has(self.requestMirror) && self.type != ''RequestMirror'')' + - message: filter.requestMirror must be specified for + RequestMirror filter.type + rule: '!(!has(self.requestMirror) && self.type == + ''RequestMirror'')' + - message: filter.requestRedirect must be nil if the + filter.type is not RequestRedirect + rule: '!(has(self.requestRedirect) && self.type != + ''RequestRedirect'')' + - message: filter.requestRedirect must be specified + for RequestRedirect filter.type + rule: '!(!has(self.requestRedirect) && self.type == + ''RequestRedirect'')' + - message: filter.urlRewrite must be nil if the filter.type + is not URLRewrite + rule: '!(has(self.urlRewrite) && self.type != ''URLRewrite'')' + - message: filter.urlRewrite must be specified for URLRewrite + filter.type + rule: '!(!has(self.urlRewrite) && self.type == ''URLRewrite'')' + - message: filter.extensionRef must be nil if the filter.type + is not ExtensionRef + rule: '!(has(self.extensionRef) && self.type != ''ExtensionRef'')' + - message: filter.extensionRef must be specified for + ExtensionRef filter.type + rule: '!(!has(self.extensionRef) && self.type == ''ExtensionRef'')' + maxItems: 16 + type: array + x-kubernetes-validations: + - message: May specify either httpRouteFilterRequestRedirect + or httpRouteFilterRequestRewrite, but not both + rule: '!(self.exists(f, f.type == ''RequestRedirect'') + && self.exists(f, f.type == ''URLRewrite''))' + - message: May specify either httpRouteFilterRequestRedirect + or httpRouteFilterRequestRewrite, but not both + rule: '!(self.exists(f, f.type == ''RequestRedirect'') + && self.exists(f, f.type == ''URLRewrite''))' + - message: RequestHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'RequestHeaderModifier').size() + <= 1 + - message: ResponseHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'ResponseHeaderModifier').size() + <= 1 + - message: RequestRedirect filter cannot be repeated + rule: self.filter(f, f.type == 'RequestRedirect').size() + <= 1 + - message: URLRewrite filter cannot be repeated + rule: self.filter(f, f.type == 'URLRewrite').size() + <= 1 + group: + default: "" + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Service + description: |- + Kind is the Kubernetes resource kind of the referent. For example + "Service". + + Defaults to "Service" when not specified. + + ExternalName services can refer to CNAME DNS records that may live + outside of the cluster and as such are difficult to reason about in + terms of conformance. They also may not be safe to forward to (see + CVE-2021-25740 for more information). Implementations SHOULD NOT + support ExternalName Services. + + Support: Core (Services with a type other than ExternalName) + + Support: Implementation-specific (Services with type ExternalName) + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the backend. When unspecified, the local + namespace is inferred. + + Note that when a namespace different than the local namespace is specified, + a ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port specifies the destination port number to use for this resource. + Port is required when the referent is a Kubernetes Service. In this + case, the port number is the service port number, not the target port. + For other resources, destination port might be derived from the referent + resource or this field. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + weight: + default: 1 + description: |- + Weight specifies the proportion of requests forwarded to the referenced + backend. This is computed as weight/(sum of all weights in this + BackendRefs list). For non-zero values, there may be some epsilon from + the exact proportion defined here depending on the precision an + implementation supports. Weight is not a percentage and the sum of + weights does not need to equal 100. + + If only one backend is specified and it has a weight greater than 0, 100% + of the traffic is forwarded to that backend. If weight is set to 0, no + traffic should be forwarded for this entry. If unspecified, weight + defaults to 1. + + Support for this field varies based on the context where used. + format: int32 + maximum: 1000000 + minimum: 0 + type: integer + required: + - name + type: object + x-kubernetes-validations: + - message: Must have port for Service reference + rule: '(size(self.group) == 0 && self.kind == ''Service'') + ? has(self.port) : true' + maxItems: 16 + type: array + filters: + description: |- + Filters define the filters that are applied to requests that match + this rule. + + Wherever possible, implementations SHOULD implement filters in the order + they are specified. + + Implementations MAY choose to implement this ordering strictly, rejecting + any combination or order of filters that can not be supported. If implementations + choose a strict interpretation of filter ordering, they MUST clearly document + that behavior. + + To reject an invalid combination or order of filters, implementations SHOULD + consider the Route Rules with this configuration invalid. If all Route Rules + in a Route are invalid, the entire Route would be considered invalid. If only + a portion of Route Rules are invalid, implementations MUST set the + "PartiallyInvalid" condition for the Route. + + Conformance-levels at this level are defined based on the type of filter: + + - ALL core filters MUST be supported by all implementations. + - Implementers are encouraged to support extended filters. + - Implementation-specific custom filters have no API guarantees across + implementations. + + Specifying the same filter multiple times is not supported unless explicitly + indicated in the filter. + + All filters are expected to be compatible with each other except for the + URLRewrite and RequestRedirect filters, which may not be combined. If an + implementation can not support other combinations of filters, they must clearly + document that limitation. In cases where incompatible or unsupported + filters are specified and cause the `Accepted` condition to be set to status + `False`, implementations may use the `IncompatibleFilters` reason to specify + this configuration error. + + Support: Core + items: + description: |- + HTTPRouteFilter defines processing steps that must be completed during the + request or response lifecycle. HTTPRouteFilters are meant as an extension + point to express processing that may be done in Gateway implementations. Some + examples include request or response modification, implementing + authentication strategies, rate-limiting, and traffic shaping. API + guarantee/conformance is defined based on the type of the filter. + properties: + extensionRef: + description: |- + ExtensionRef is an optional, implementation-specific extension to the + "filter" behavior. For example, resource "myroutefilter" in group + "networking.example.net"). ExtensionRef MUST NOT be used for core and + extended filters. + + This filter can be used multiple times within the same rule. + + Support: Implementation-specific + properties: + group: + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: Kind is kind of the referent. For example + "HTTPRoute" or "Service". + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + required: + - group + - kind + - name + type: object + requestHeaderModifier: + description: |- + RequestHeaderModifier defines a schema for a filter that modifies request + headers. + + Support: Core + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + requestMirror: + description: |+ + RequestMirror defines a schema for a filter that mirrors requests. + Requests are sent to the specified destination, but responses from + that destination are ignored. + + This filter can be used multiple times within the same rule. Note that + not all implementations will be able to support mirroring to multiple + backends. + + Support: Extended + + properties: + backendRef: + description: |- + BackendRef references a resource where mirrored requests are sent. + + Mirrored requests must be sent only to a single destination endpoint + within this BackendRef, irrespective of how many endpoints are present + within this BackendRef. + + If the referent cannot be found, this BackendRef is invalid and must be + dropped from the Gateway. The controller must ensure the "ResolvedRefs" + condition on the Route status is set to `status: False` and not configure + this backend in the underlying implementation. + + If there is a cross-namespace reference to an *existing* object + that is not allowed by a ReferenceGrant, the controller must ensure the + "ResolvedRefs" condition on the Route is set to `status: False`, + with the "RefNotPermitted" reason and not configure this backend in the + underlying implementation. + + In either error case, the Message of the `ResolvedRefs` Condition + should be used to provide more detail about the problem. + + Support: Extended for Kubernetes Service + + Support: Implementation-specific for any other resource + properties: + group: + default: "" + description: |- + Group is the group of the referent. For example, "gateway.networking.k8s.io". + When unspecified or empty string, core API group is inferred. + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Service + description: |- + Kind is the Kubernetes resource kind of the referent. For example + "Service". + + Defaults to "Service" when not specified. + + ExternalName services can refer to CNAME DNS records that may live + outside of the cluster and as such are difficult to reason about in + terms of conformance. They also may not be safe to forward to (see + CVE-2021-25740 for more information). Implementations SHOULD NOT + support ExternalName Services. + + Support: Core (Services with a type other than ExternalName) + + Support: Implementation-specific (Services with type ExternalName) + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: Name is the name of the referent. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the backend. When unspecified, the local + namespace is inferred. + + Note that when a namespace different than the local namespace is specified, + a ReferenceGrant object is required in the referent namespace to allow that + namespace's owner to accept the reference. See the ReferenceGrant + documentation for details. + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port specifies the destination port number to use for this resource. + Port is required when the referent is a Kubernetes Service. In this + case, the port number is the service port number, not the target port. + For other resources, destination port might be derived from the referent + resource or this field. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + required: + - name + type: object + x-kubernetes-validations: + - message: Must have port for Service reference + rule: '(size(self.group) == 0 && self.kind == ''Service'') + ? has(self.port) : true' + required: + - backendRef + type: object + requestRedirect: + description: |- + RequestRedirect defines a schema for a filter that responds to the + request with an HTTP redirection. + + Support: Core + properties: + hostname: + description: |- + Hostname is the hostname to be used in the value of the `Location` + header in the response. + When empty, the hostname in the `Host` header of the request is used. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines parameters used to modify the path of the incoming request. + The modified path is then used to construct the `Location` header. When + empty, the request path is used as-is. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified when + type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? has(self.replaceFullPath) + : true' + - message: type must be 'ReplaceFullPath' when replaceFullPath + is set + rule: 'has(self.replaceFullPath) ? self.type == + ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified when + type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' ? has(self.replacePrefixMatch) + : true' + - message: type must be 'ReplacePrefixMatch' when + replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + port: + description: |- + Port is the port to be used in the value of the `Location` + header in the response. + + If no port is specified, the redirect port MUST be derived using the + following rules: + + * If redirect scheme is not-empty, the redirect port MUST be the well-known + port associated with the redirect scheme. Specifically "http" to port 80 + and "https" to port 443. If the redirect scheme does not have a + well-known port, the listener port of the Gateway SHOULD be used. + * If redirect scheme is empty, the redirect port MUST be the Gateway + Listener port. + + Implementations SHOULD NOT add the port number in the 'Location' + header in the following cases: + + * A Location header that will use HTTP (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 80. + * A Location header that will use HTTPS (whether that is determined via + the Listener protocol or the Scheme field) _and_ use port 443. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + scheme: + description: |- + Scheme is the scheme to be used in the value of the `Location` header in + the response. When empty, the scheme of the request is used. + + Scheme redirects can affect the port of the redirect, for more information, + refer to the documentation for the port field of this filter. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Extended + enum: + - http + - https + type: string + statusCode: + default: 302 + description: |- + StatusCode is the HTTP status code to be used in response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + + Support: Core + enum: + - 301 + - 302 + type: integer + type: object + responseHeaderModifier: + description: |- + ResponseHeaderModifier defines a schema for a filter that modifies response + headers. + + Support: Extended + properties: + add: + description: |- + Add adds the given header(s) (name, value) to the request + before the action. It appends to any existing values associated + with the header name. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + add: + - name: "my-header" + value: "bar,baz" + + Output: + GET /foo HTTP/1.1 + my-header: foo,bar,baz + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + remove: + description: |- + Remove the given header(s) from the HTTP request before the action. The + value of Remove is a list of HTTP header names. Note that the header + names are case-insensitive (see + https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). + + Input: + GET /foo HTTP/1.1 + my-header1: foo + my-header2: bar + my-header3: baz + + Config: + remove: ["my-header1", "my-header3"] + + Output: + GET /foo HTTP/1.1 + my-header2: bar + items: + type: string + maxItems: 16 + type: array + x-kubernetes-list-type: set + set: + description: |- + Set overwrites the request with the given header (name, value) + before the action. + + Input: + GET /foo HTTP/1.1 + my-header: foo + + Config: + set: + - name: "my-header" + value: "bar" + + Output: + GET /foo HTTP/1.1 + my-header: bar + items: + description: HTTPHeader represents an HTTP Header + name and value as defined by RFC 7230. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, the first entry with + an equivalent name MUST be considered for a match. Subsequent entries + with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + value: + description: Value is the value of HTTP Header + to be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + type: + description: |- + Type identifies the type of filter to apply. As with other API fields, + types are classified into three conformance levels: + + - Core: Filter types and their corresponding configuration defined by + "Support: Core" in this package, e.g. "RequestHeaderModifier". All + implementations must support core filters. + + - Extended: Filter types and their corresponding configuration defined by + "Support: Extended" in this package, e.g. "RequestMirror". Implementers + are encouraged to support extended filters. + + - Implementation-specific: Filters that are defined and supported by + specific vendors. + In the future, filters showing convergence in behavior across multiple + implementations will be considered for inclusion in extended or core + conformance levels. Filter-specific configuration for such filters + is specified using the ExtensionRef field. `Type` should be set to + "ExtensionRef" for custom filters. + + Implementers are encouraged to define custom implementation types to + extend the core API with implementation-specific behavior. + + If a reference to a custom filter type cannot be resolved, the filter + MUST NOT be skipped. Instead, requests that would have been processed by + that filter MUST receive a HTTP error response. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - RequestHeaderModifier + - ResponseHeaderModifier + - RequestMirror + - RequestRedirect + - URLRewrite + - ExtensionRef + type: string + urlRewrite: + description: |- + URLRewrite defines a schema for a filter that modifies a request during forwarding. + + Support: Extended + properties: + hostname: + description: |- + Hostname is the value to be used to replace the Host header value during + forwarding. + + Support: Extended + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + path: + description: |- + Path defines a path rewrite. + + Support: Extended + properties: + replaceFullPath: + description: |- + ReplaceFullPath specifies the value with which to replace the full path + of a request during a rewrite or redirect. + maxLength: 1024 + type: string + replacePrefixMatch: + description: |- + ReplacePrefixMatch specifies the value with which to replace the prefix + match of a request during a rewrite or redirect. For example, a request + to "/foo/bar" with a prefix match of "/foo" and a ReplacePrefixMatch + of "/xyz" would be modified to "/xyz/bar". + + Note that this matches the behavior of the PathPrefix match type. This + matches full path elements. A path element refers to the list of labels + in the path split by the `/` separator. When specified, a trailing `/` is + ignored. For example, the paths `/abc`, `/abc/`, and `/abc/def` would all + match the prefix `/abc`, but the path `/abcd` would not. + + ReplacePrefixMatch is only compatible with a `PathPrefix` HTTPRouteMatch. + Using any other HTTPRouteMatch type on the same HTTPRouteRule will result in + the implementation setting the Accepted Condition for the Route to `status: False`. + + Request Path | Prefix Match | Replace Prefix | Modified Path + maxLength: 1024 + type: string + type: + description: |- + Type defines the type of path modifier. Additional types may be + added in a future release of the API. + + Note that values may be added to this enum, implementations + must ensure that unknown values will not cause a crash. + + Unknown values here must result in the implementation setting the + Accepted Condition for the Route to `status: False`, with a + Reason of `UnsupportedValue`. + enum: + - ReplaceFullPath + - ReplacePrefixMatch + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: replaceFullPath must be specified when + type is set to 'ReplaceFullPath' + rule: 'self.type == ''ReplaceFullPath'' ? has(self.replaceFullPath) + : true' + - message: type must be 'ReplaceFullPath' when replaceFullPath + is set + rule: 'has(self.replaceFullPath) ? self.type == + ''ReplaceFullPath'' : true' + - message: replacePrefixMatch must be specified when + type is set to 'ReplacePrefixMatch' + rule: 'self.type == ''ReplacePrefixMatch'' ? has(self.replacePrefixMatch) + : true' + - message: type must be 'ReplacePrefixMatch' when + replacePrefixMatch is set + rule: 'has(self.replacePrefixMatch) ? self.type + == ''ReplacePrefixMatch'' : true' + type: object + required: + - type + type: object + x-kubernetes-validations: + - message: filter.requestHeaderModifier must be nil if the + filter.type is not RequestHeaderModifier + rule: '!(has(self.requestHeaderModifier) && self.type != + ''RequestHeaderModifier'')' + - message: filter.requestHeaderModifier must be specified + for RequestHeaderModifier filter.type + rule: '!(!has(self.requestHeaderModifier) && self.type == + ''RequestHeaderModifier'')' + - message: filter.responseHeaderModifier must be nil if the + filter.type is not ResponseHeaderModifier + rule: '!(has(self.responseHeaderModifier) && self.type != + ''ResponseHeaderModifier'')' + - message: filter.responseHeaderModifier must be specified + for ResponseHeaderModifier filter.type + rule: '!(!has(self.responseHeaderModifier) && self.type + == ''ResponseHeaderModifier'')' + - message: filter.requestMirror must be nil if the filter.type + is not RequestMirror + rule: '!(has(self.requestMirror) && self.type != ''RequestMirror'')' + - message: filter.requestMirror must be specified for RequestMirror + filter.type + rule: '!(!has(self.requestMirror) && self.type == ''RequestMirror'')' + - message: filter.requestRedirect must be nil if the filter.type + is not RequestRedirect + rule: '!(has(self.requestRedirect) && self.type != ''RequestRedirect'')' + - message: filter.requestRedirect must be specified for RequestRedirect + filter.type + rule: '!(!has(self.requestRedirect) && self.type == ''RequestRedirect'')' + - message: filter.urlRewrite must be nil if the filter.type + is not URLRewrite + rule: '!(has(self.urlRewrite) && self.type != ''URLRewrite'')' + - message: filter.urlRewrite must be specified for URLRewrite + filter.type + rule: '!(!has(self.urlRewrite) && self.type == ''URLRewrite'')' + - message: filter.extensionRef must be nil if the filter.type + is not ExtensionRef + rule: '!(has(self.extensionRef) && self.type != ''ExtensionRef'')' + - message: filter.extensionRef must be specified for ExtensionRef + filter.type + rule: '!(!has(self.extensionRef) && self.type == ''ExtensionRef'')' + maxItems: 16 + type: array + x-kubernetes-validations: + - message: May specify either httpRouteFilterRequestRedirect + or httpRouteFilterRequestRewrite, but not both + rule: '!(self.exists(f, f.type == ''RequestRedirect'') && + self.exists(f, f.type == ''URLRewrite''))' + - message: RequestHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'RequestHeaderModifier').size() + <= 1 + - message: ResponseHeaderModifier filter cannot be repeated + rule: self.filter(f, f.type == 'ResponseHeaderModifier').size() + <= 1 + - message: RequestRedirect filter cannot be repeated + rule: self.filter(f, f.type == 'RequestRedirect').size() <= + 1 + - message: URLRewrite filter cannot be repeated + rule: self.filter(f, f.type == 'URLRewrite').size() <= 1 + matches: + default: + - path: + type: PathPrefix + value: / + description: |- + Matches define conditions used for matching the rule against incoming + HTTP requests. Each match is independent, i.e. this rule will be matched + if **any** one of the matches is satisfied. + + For example, take the following matches configuration: + + ``` + matches: + - path: + value: "/foo" + headers: + - name: "version" + value: "v2" + - path: + value: "/v2/foo" + ``` + + For a request to match against this rule, a request must satisfy + EITHER of the two conditions: + + - path prefixed with `/foo` AND contains the header `version: v2` + - path prefix of `/v2/foo` + + See the documentation for HTTPRouteMatch on how to specify multiple + match conditions that should be ANDed together. + + If no matches are specified, the default is a prefix + path match on "/", which has the effect of matching every + HTTP request. + + Proxy or Load Balancer routing configuration generated from HTTPRoutes + MUST prioritize matches based on the following criteria, continuing on + ties. Across all rules specified on applicable Routes, precedence must be + given to the match having: + + * "Exact" path match. + * "Prefix" path match with largest number of characters. + * Method match. + * Largest number of header matches. + * Largest number of query param matches. + + Note: The precedence of RegularExpression path matches are implementation-specific. + + If ties still exist across multiple Routes, matching precedence MUST be + determined in order of the following criteria, continuing on ties: + + * The oldest Route based on creation timestamp. + * The Route appearing first in alphabetical order by + "{namespace}/{name}". + + If ties still exist within an HTTPRoute, matching precedence MUST be granted + to the FIRST matching rule (in list order) with a match meeting the above + criteria. + + When no rules matching a request have been successfully attached to the + parent a request is coming from, a HTTP 404 status code MUST be returned. + items: + description: "HTTPRouteMatch defines the predicate used to + match requests to a given\naction. Multiple match types + are ANDed together, i.e. the match will\nevaluate to true + only if all conditions are satisfied.\n\nFor example, the + match below will match a HTTP request only if its path\nstarts + with `/foo` AND it contains the `version: v1` header:\n\n```\nmatch:\n\n\tpath:\n\t + \ value: \"/foo\"\n\theaders:\n\t- name: \"version\"\n\t + \ value \"v1\"\n\n```" + properties: + headers: + description: |- + Headers specifies HTTP request header matchers. Multiple match values are + ANDed together, meaning, a request must match all the specified headers + to select the route. + items: + description: |- + HTTPHeaderMatch describes how to select a HTTP route by matching HTTP request + headers. + properties: + name: + description: |- + Name is the name of the HTTP Header to be matched. Name matching MUST be + case insensitive. (See https://tools.ietf.org/html/rfc7230#section-3.2). + + If multiple entries specify equivalent header names, only the first + entry with an equivalent name MUST be considered for a match. Subsequent + entries with an equivalent header name MUST be ignored. Due to the + case-insensitivity of header names, "foo" and "Foo" are considered + equivalent. + + When a header is repeated in an HTTP request, it is + implementation-specific behavior as to how this is represented. + Generally, proxies should follow the guidance from the RFC: + https://www.rfc-editor.org/rfc/rfc7230.html#section-3.2.2 regarding + processing a repeated header, with special handling for "Set-Cookie". + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + type: + default: Exact + description: |- + Type specifies how to match against the value of the header. + + Support: Core (Exact) + + Support: Implementation-specific (RegularExpression) + + Since RegularExpression HeaderMatchType has implementation-specific + conformance, implementations can support POSIX, PCRE or any other dialects + of regular expressions. Please read the implementation's documentation to + determine the supported dialect. + enum: + - Exact + - RegularExpression + type: string + value: + description: Value is the value of HTTP Header to + be matched. + maxLength: 4096 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + method: + description: |- + Method specifies HTTP method matcher. + When specified, this route will be matched only if the request has the + specified method. + + Support: Extended + enum: + - GET + - HEAD + - POST + - PUT + - DELETE + - CONNECT + - OPTIONS + - TRACE + - PATCH + type: string + path: + default: + type: PathPrefix + value: / + description: |- + Path specifies a HTTP request path matcher. If this field is not + specified, a default prefix match on the "/" path is provided. + properties: + type: + default: PathPrefix + description: |- + Type specifies how to match against the path Value. + + Support: Core (Exact, PathPrefix) + + Support: Implementation-specific (RegularExpression) + enum: + - Exact + - PathPrefix + - RegularExpression + type: string + value: + default: / + description: Value of the HTTP path to match against. + maxLength: 1024 + type: string + type: object + x-kubernetes-validations: + - message: value must be an absolute path and start with + '/' when type one of ['Exact', 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? self.value.startsWith(''/'') + : true' + - message: must not contain '//' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''//'') + : true' + - message: must not contain '/./' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''/./'') + : true' + - message: must not contain '/../' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''/../'') + : true' + - message: must not contain '%2f' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''%2f'') + : true' + - message: must not contain '%2F' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''%2F'') + : true' + - message: must not contain '#' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.contains(''#'') + : true' + - message: must not end with '/..' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.endsWith(''/..'') + : true' + - message: must not end with '/.' when type one of ['Exact', + 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? !self.value.endsWith(''/.'') + : true' + - message: type must be one of ['Exact', 'PathPrefix', + 'RegularExpression'] + rule: self.type in ['Exact','PathPrefix'] || self.type + == 'RegularExpression' + - message: must only contain valid characters (matching + ^(?:[-A-Za-z0-9/._~!$&'()*+,;=:@]|[%][0-9a-fA-F]{2})+$) + for types ['Exact', 'PathPrefix'] + rule: '(self.type in [''Exact'',''PathPrefix'']) ? self.value.matches(r"""^(?:[-A-Za-z0-9/._~!$&''()*+,;=:@]|[%][0-9a-fA-F]{2})+$""") + : true' + queryParams: + description: |- + QueryParams specifies HTTP query parameter matchers. Multiple match + values are ANDed together, meaning, a request must match all the + specified query parameters to select the route. + + Support: Extended + items: + description: |- + HTTPQueryParamMatch describes how to select a HTTP route by matching HTTP + query parameters. + properties: + name: + description: |- + Name is the name of the HTTP query param to be matched. This must be an + exact string match. (See + https://tools.ietf.org/html/rfc7230#section-2.7.3). + + If multiple entries specify equivalent query param names, only the first + entry with an equivalent name MUST be considered for a match. Subsequent + entries with an equivalent query param name MUST be ignored. + + If a query param is repeated in an HTTP request, the behavior is + purposely left undefined, since different data planes have different + capabilities. However, it is *recommended* that implementations should + match against the first value of the param if the data plane supports it, + as this behavior is expected in other load balancing contexts outside of + the Gateway API. + + Users SHOULD NOT route traffic based on repeated query params to guard + themselves against potential differences in the implementations. + maxLength: 256 + minLength: 1 + pattern: ^[A-Za-z0-9!#$%&'*+\-.^_\x60|~]+$ + type: string + type: + default: Exact + description: |- + Type specifies how to match against the value of the query parameter. + + Support: Extended (Exact) + + Support: Implementation-specific (RegularExpression) + + Since RegularExpression QueryParamMatchType has Implementation-specific + conformance, implementations can support POSIX, PCRE or any other + dialects of regular expressions. Please read the implementation's + documentation to determine the supported dialect. + enum: + - Exact + - RegularExpression + type: string + value: + description: Value is the value of HTTP query param + to be matched. + maxLength: 1024 + minLength: 1 + type: string + required: + - name + - value + type: object + maxItems: 16 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + maxItems: 64 + type: array + timeouts: + description: |- + Timeouts defines the timeouts that can be configured for an HTTP request. + + Support: Extended + properties: + backendRequest: + description: |- + BackendRequest specifies a timeout for an individual request from the gateway + to a backend. This covers the time from when the request first starts being + sent from the gateway to when the full response has been received from the backend. + + Setting a timeout to the zero duration (e.g. "0s") SHOULD disable the timeout + completely. Implementations that cannot completely disable the timeout MUST + instead interpret the zero duration as the longest possible value to which + the timeout can be set. + + An entire client HTTP transaction with a gateway, covered by the Request timeout, + may result in more than one call from the gateway to the destination backend, + for example, if automatic retries are supported. + + The value of BackendRequest must be a Gateway API Duration string as defined by + GEP-2257. When this field is unspecified, its behavior is implementation-specific; + when specified, the value of BackendRequest must be no more than the value of the + Request timeout (since the Request timeout encompasses the BackendRequest timeout). + + Support: Extended + pattern: ^([0-9]{1,5}(h|m|s|ms)){1,4}$ + type: string + request: + description: |- + Request specifies the maximum duration for a gateway to respond to an HTTP request. + If the gateway has not been able to respond before this deadline is met, the gateway + MUST return a timeout error. + + For example, setting the `rules.timeouts.request` field to the value `10s` in an + `HTTPRoute` will cause a timeout if a client request is taking longer than 10 seconds + to complete. + + Setting a timeout to the zero duration (e.g. "0s") SHOULD disable the timeout + completely. Implementations that cannot completely disable the timeout MUST + instead interpret the zero duration as the longest possible value to which + the timeout can be set. + + This timeout is intended to cover as close to the whole request-response transaction + as possible although an implementation MAY choose to start the timeout after the entire + request stream has been received instead of immediately after the transaction is + initiated by the client. + + The value of Request is a Gateway API Duration string as defined by GEP-2257. When this + field is unspecified, request timeout behavior is implementation-specific. + + Support: Extended + pattern: ^([0-9]{1,5}(h|m|s|ms)){1,4}$ + type: string + type: object + x-kubernetes-validations: + - message: backendRequest timeout cannot be longer than request + timeout + rule: '!(has(self.request) && has(self.backendRequest) && + duration(self.request) != duration(''0s'') && duration(self.backendRequest) + > duration(self.request))' + type: object + x-kubernetes-validations: + - message: RequestRedirect filter must not be used together with + backendRefs + rule: '(has(self.backendRefs) && size(self.backendRefs) > 0) ? + (!has(self.filters) || self.filters.all(f, !has(f.requestRedirect))): + true' + - message: When using RequestRedirect filter with path.replacePrefixMatch, + exactly one PathPrefix match must be specified + rule: '(has(self.filters) && self.filters.exists_one(f, has(f.requestRedirect) + && has(f.requestRedirect.path) && f.requestRedirect.path.type + == ''ReplacePrefixMatch'' && has(f.requestRedirect.path.replacePrefixMatch))) + ? ((size(self.matches) != 1 || !has(self.matches[0].path) || + self.matches[0].path.type != ''PathPrefix'') ? false : true) + : true' + - message: When using URLRewrite filter with path.replacePrefixMatch, + exactly one PathPrefix match must be specified + rule: '(has(self.filters) && self.filters.exists_one(f, has(f.urlRewrite) + && has(f.urlRewrite.path) && f.urlRewrite.path.type == ''ReplacePrefixMatch'' + && has(f.urlRewrite.path.replacePrefixMatch))) ? ((size(self.matches) + != 1 || !has(self.matches[0].path) || self.matches[0].path.type + != ''PathPrefix'') ? false : true) : true' + - message: Within backendRefs, when using RequestRedirect filter + with path.replacePrefixMatch, exactly one PathPrefix match must + be specified + rule: '(has(self.backendRefs) && self.backendRefs.exists_one(b, + (has(b.filters) && b.filters.exists_one(f, has(f.requestRedirect) + && has(f.requestRedirect.path) && f.requestRedirect.path.type + == ''ReplacePrefixMatch'' && has(f.requestRedirect.path.replacePrefixMatch))) + )) ? ((size(self.matches) != 1 || !has(self.matches[0].path) + || self.matches[0].path.type != ''PathPrefix'') ? false : true) + : true' + - message: Within backendRefs, When using URLRewrite filter with + path.replacePrefixMatch, exactly one PathPrefix match must be + specified + rule: '(has(self.backendRefs) && self.backendRefs.exists_one(b, + (has(b.filters) && b.filters.exists_one(f, has(f.urlRewrite) + && has(f.urlRewrite.path) && f.urlRewrite.path.type == ''ReplacePrefixMatch'' + && has(f.urlRewrite.path.replacePrefixMatch))) )) ? ((size(self.matches) + != 1 || !has(self.matches[0].path) || self.matches[0].path.type + != ''PathPrefix'') ? false : true) : true' + maxItems: 16 + type: array + x-kubernetes-validations: + - message: While 16 rules and 64 matches per rule are allowed, the + total number of matches across all rules in a route must be less + than 128 + rule: '(self.size() > 0 ? self[0].matches.size() : 0) + (self.size() + > 1 ? self[1].matches.size() : 0) + (self.size() > 2 ? self[2].matches.size() + : 0) + (self.size() > 3 ? self[3].matches.size() : 0) + (self.size() + > 4 ? self[4].matches.size() : 0) + (self.size() > 5 ? self[5].matches.size() + : 0) + (self.size() > 6 ? self[6].matches.size() : 0) + (self.size() + > 7 ? self[7].matches.size() : 0) + (self.size() > 8 ? self[8].matches.size() + : 0) + (self.size() > 9 ? self[9].matches.size() : 0) + (self.size() + > 10 ? self[10].matches.size() : 0) + (self.size() > 11 ? self[11].matches.size() + : 0) + (self.size() > 12 ? self[12].matches.size() : 0) + (self.size() + > 13 ? self[13].matches.size() : 0) + (self.size() > 14 ? self[14].matches.size() + : 0) + (self.size() > 15 ? self[15].matches.size() : 0) <= 128' + type: object + status: + description: Status defines the current state of HTTPRoute. + properties: + parents: + description: |- + Parents is a list of parent resources (usually Gateways) that are + associated with the route, and the status of the route with respect to + each parent. When this route attaches to a parent, the controller that + manages the parent must add an entry to this list when the controller + first sees the route and should update the entry as appropriate when the + route or gateway is modified. + + Note that parent references that cannot be resolved by an implementation + of this API will not be added to this list. Implementations of this API + can only populate Route status for the Gateways/parent resources they are + responsible for. + + A maximum of 32 Gateways will be represented in this list. An empty list + means the route has not been attached to any Gateway. + items: + description: |- + RouteParentStatus describes the status of a route with respect to an + associated Parent. + properties: + conditions: + description: |- + Conditions describes the status of the route with respect to the Gateway. + Note that the route's availability is also subject to the Gateway's own + status conditions and listener status. + + If the Route's ParentRef specifies an existing Gateway that supports + Routes of this kind AND that Gateway's controller has sufficient access, + then that Gateway's controller MUST set the "Accepted" condition on the + Route, to indicate whether the route has been accepted or rejected by the + Gateway, and why. + + A Route MUST be considered "Accepted" if at least one of the Route's + rules is implemented by the Gateway. + + There are a number of cases where the "Accepted" condition may not be set + due to lack of controller visibility, that includes when: + + * The Route refers to a non-existent parent. + * The Route is of a type that the controller does not support. + * The Route is in a namespace the controller does not have access to. + items: + description: Condition contains details for one aspect of + the current state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, + Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 8 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + controllerName: + description: |- + ControllerName is a domain/path string that indicates the name of the + controller that wrote this status. This corresponds with the + controllerName field on GatewayClass. + + Example: "example.net/gateway-controller". + + The format of this field is DOMAIN "/" PATH, where DOMAIN and PATH are + valid Kubernetes names + (https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names). + + Controllers MUST populate this field when writing status. Controllers should ensure that + entries to status populated with their ControllerName are cleaned up when they are no + longer necessary. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[A-Za-z0-9\/\-._~%!$&'()*+,;=:]+$ + type: string + parentRef: + description: |- + ParentRef corresponds with a ParentRef in the spec that this + RouteParentStatus struct describes the status of. + properties: + group: + default: gateway.networking.k8s.io + description: |- + Group is the group of the referent. + When unspecified, "gateway.networking.k8s.io" is inferred. + To set the core API group (such as for a "Service" kind referent), + Group must be explicitly set to "" (empty string). + + Support: Core + maxLength: 253 + pattern: ^$|^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + default: Gateway + description: |- + Kind is kind of the referent. + + There are two kinds of parent resources with "Core" support: + + * Gateway (Gateway conformance profile) + * Service (Mesh conformance profile, ClusterIP Services only) + + Support for other resources is Implementation-Specific. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + Name is the name of the referent. + + Support: Core + maxLength: 253 + minLength: 1 + type: string + namespace: + description: |- + Namespace is the namespace of the referent. When unspecified, this refers + to the local namespace of the Route. + + Note that there are specific rules for ParentRefs which cross namespace + boundaries. Cross-namespace references are only valid if they are explicitly + allowed by something in the namespace they are referring to. For example: + Gateway has the AllowedRoutes field, and ReferenceGrant provides a + generic way to enable any other kind of cross-namespace reference. + + + + Support: Core + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + port: + description: |- + Port is the network port this Route targets. It can be interpreted + differently based on the type of parent resource. + + When the parent resource is a Gateway, this targets all listeners + listening on the specified port that also support this kind of Route(and + select this Route). It's not recommended to set `Port` unless the + networking behaviors specified in a Route must apply to a specific port + as opposed to a listener(s) whose port(s) may be changed. When both Port + and SectionName are specified, the name and port of the selected listener + must match both specified values. + + + + Implementations MAY choose to support other parent resources. + Implementations supporting other types of parent resources MUST clearly + document how/if Port is interpreted. + + For the purpose of status, an attachment is considered successful as + long as the parent resource accepts it partially. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment + from the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, + the Route MUST be considered detached from the Gateway. + + Support: Extended + format: int32 + maximum: 65535 + minimum: 1 + type: integer + sectionName: + description: |- + SectionName is the name of a section within the target resource. In the + following resources, SectionName is interpreted as the following: + + * Gateway: Listener name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + * Service: Port name. When both Port (experimental) and SectionName + are specified, the name and port of the selected listener must match + both specified values. + + Implementations MAY choose to support attaching Routes to other resources. + If that is the case, they MUST clearly document how SectionName is + interpreted. + + When unspecified (empty string), this will reference the entire resource. + For the purpose of status, an attachment is considered successful if at + least one section in the parent resource accepts it. For example, Gateway + listeners can restrict which Routes can attach to them by Route kind, + namespace, or hostname. If 1 of 2 Gateway listeners accept attachment from + the referencing Route, the Route MUST be considered successfully + attached. If no Gateway listeners accept attachment from this Route, the + Route MUST be considered detached from the Gateway. + + Support: Core + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - name + type: object + required: + - controllerName + - parentRef + type: object + maxItems: 32 + type: array + required: + - parents + type: object + required: + - spec + type: object + served: true + storage: false + subresources: + status: {} +status: + acceptedNames: + kind: "" + plural: "" + conditions: null + storedVersions: null diff --git a/controllers/controller/devworkspacerouting/util_test.go b/controllers/controller/devworkspacerouting/util_test.go index d386f4635..a6e5d436d 100644 --- a/controllers/controller/devworkspacerouting/util_test.go +++ b/controllers/controller/devworkspacerouting/util_test.go @@ -24,6 +24,7 @@ import ( . "github.com/onsi/gomega" routeV1 "github.com/openshift/api/route/v1" crclient "sigs.k8s.io/controller-runtime/pkg/client" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" @@ -164,6 +165,20 @@ func deleteIngress(endpointName string, namespace string) { deleteObject(&createdIngress) } +func deleteHTTPRoute(endpointName string, namespace string, isRedirect bool) { + createdHTTPRoute := gwapiv1.HTTPRoute{} + routeName := common.RouteName(testWorkspaceID, endpointName) + if isRedirect { + routeName = routeName + "-http-redirect" + } + httpRouteNamespacedName := namespacedName(routeName, namespace) + Eventually(func() bool { + err := k8sClient.Get(ctx, httpRouteNamespacedName, &createdHTTPRoute) + return err == nil + }, timeout, interval).Should(BeTrue(), "HTTPRoute should exist in cluster") + deleteObject(&createdHTTPRoute) +} + func deleteDevWorkspaceRouting(name string) { dwrNN := namespacedName(name, testNamespace) dwr := &controllerv1alpha1.DevWorkspaceRouting{} diff --git a/deploy/templates/components/rbac/role.yaml b/deploy/templates/components/rbac/role.yaml index e660f82fc..57dc31600 100644 --- a/deploy/templates/components/rbac/role.yaml +++ b/deploy/templates/components/rbac/role.yaml @@ -182,6 +182,12 @@ rules: - create - get - update +- apiGroups: + - gateway.networking.k8s.io + resources: + - httproutes + verbs: + - '*' - apiGroups: - image.openshift.io resources: diff --git a/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml b/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml index 0352ebc0d..f316eb757 100644 --- a/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml +++ b/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml @@ -56,6 +56,32 @@ spec: specifies an empty `.spec.routingClass`. Supported routingClasses can be defined in other controllers. If not specified, the default value of "basic" is used. type: string + gatewayRef: + description: |- + GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + should attach to when using the 'gateway-api' routing class. This field is required + when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + properties: + gatewayClassName: + default: nginx + description: |- + GatewayClassName is the name of the GatewayClass to use. + This is used for validation and informational purposes. + Defaults to "nginx" if not specified. + type: string + name: + description: Name is the name of the Gateway resource + type: string + namespace: + description: |- + Namespace is the namespace of the Gateway resource. + If not specified, HTTPRoutes will reference a Gateway in the same namespace + as the DevWorkspace. + type: string + required: + - name + type: object proxyConfig: description: |- ProxyConfig defines the proxy settings that should be used for all DevWorkspaces. diff --git a/go.mod b/go.mod index 9627f014e..fc22ce582 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( k8s.io/client-go v0.37.0 k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 sigs.k8s.io/controller-runtime v0.25.2 + sigs.k8s.io/gateway-api v1.6.3 sigs.k8s.io/yaml v1.6.0 ) @@ -75,7 +76,7 @@ require ( github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect github.com/google/cel-go v0.29.2 // indirect - github.com/google/gnostic-models v0.7.0 // indirect + github.com/google/gnostic-models v0.7.1 // indirect github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect diff --git a/go.sum b/go.sum index 2cba35fb1..092310c3d 100644 --- a/go.sum +++ b/go.sum @@ -117,8 +117,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/cel-go v0.29.2 h1:ZtDxkeiMmz0mxbKDYiNkE5Lk7V5edMRcaaDf2jX002k= github.com/google/cel-go v0.29.2/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= -github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= -github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= +github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -355,6 +355,8 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 h1:/YpDJ4vReG7Zm sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0/go.mod h1:tJo1aepTXyR+8Xs3sUsGBDk4Ub2AM5dPAPKJx0mpm5c= sigs.k8s.io/controller-runtime v0.25.2 h1:bEkK3PVOIVK9X8QWLGVhJgmFc++47vfT6wakSzAOLsQ= sigs.k8s.io/controller-runtime v0.25.2/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= +sigs.k8s.io/gateway-api v1.6.3 h1:lKpJa5bGlraC/QeACvCpsHLdmO6y0iKfzVl6gzaFEYc= +sigs.k8s.io/gateway-api v1.6.3/go.mod h1:FVfx3t389ybeXOqvDghLbdvJdSCfI/PReqCUI3lu3mY= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= From 9825053051c65a9981f6c3ce79646c39c6210205 Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Thu, 21 May 2026 15:37:35 -0400 Subject: [PATCH 2/8] feat(routing): complete Gateway API solver integration, fix spec drift and watches Signed-off-by: Badre Tejado-Imam --- .../devworkspacerouting/devworkspacerouting_controller.go | 4 +++- .../devworkspacerouting_controller_test.go | 4 ++-- .../devworkspacerouting/solvers/gateway_api_solver.go | 2 +- main.go | 2 ++ pkg/config/sync.go | 3 +++ pkg/provision/sync/diff.go | 2 ++ pkg/provision/sync/diffopts.go | 8 ++++++++ 7 files changed, 21 insertions(+), 4 deletions(-) diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index 8b2d6ba21..2e964f374 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -36,6 +36,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/reconcile" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" "github.com/devfile/devworkspace-operator/controllers/controller/devworkspacerouting/solvers" @@ -454,7 +455,8 @@ func (r *DevWorkspaceRoutingReconciler) SetupWithManager(mgr ctrl.Manager) error }). For(&controllerv1alpha1.DevWorkspaceRouting{}). Owns(&corev1.Service{}). - Owns(&networkingv1.Ingress{}) + Owns(&networkingv1.Ingress{}). + Owns(&gwapiv1.HTTPRoute{}) if infrastructure.IsOpenShift() { bld.Owns(&routeV1.Route{}) } diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go index 568c945a1..333c07fa7 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go @@ -624,8 +624,8 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { if filter.Type == gwapiv1.HTTPRouteFilterRequestRedirect { hasRedirectFilter = true Expect(filter.RequestRedirect).ShouldNot(BeNil(), "Redirect filter should have RequestRedirect configuration") - Expect(*filter.RequestRedirect.Scheme).Should(Equal(gwapiv1.HTTPSProtocolType), "Redirect should be to HTTPS") - Expect(*filter.RequestRedirect.StatusCode).Should(Equal(308), "Redirect should use 308 status code") + Expect(*filter.RequestRedirect.Scheme).Should(Equal("https"), "Redirect should be to HTTPS") + Expect(*filter.RequestRedirect.StatusCode).Should(Equal(301), "Redirect should use 301 status code") } } Expect(hasRedirectFilter).Should(BeTrue(), "HTTP redirect HTTPRoute should have a redirect filter") diff --git a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go index 5e6839201..882beb219 100644 --- a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go +++ b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go @@ -131,7 +131,7 @@ func (s *GatewayAPISolver) createHTTPRedirectRoute( routeName := fmt.Sprintf("%s-http-redirect", common.RouteName(workspaceMeta.DevWorkspaceId, endpointName)) httpsScheme := "https" - statusCode := 308 + statusCode := 301 pathPrefix := gwapiv1.PathMatchPathPrefix pathValue := "/" diff --git a/main.go b/main.go index 71464a6c0..0ed16ef1b 100644 --- a/main.go +++ b/main.go @@ -60,6 +60,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" ctrl_webhook "sigs.k8s.io/controller-runtime/pkg/webhook" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" // +kubebuilder:scaffold:imports ) @@ -81,6 +82,7 @@ func init() { utilruntime.Must(controllerv1alpha1.AddToScheme(scheme)) utilruntime.Must(dwv1.AddToScheme(scheme)) utilruntime.Must(dwv2.AddToScheme(scheme)) + utilruntime.Must(gwapiv1.AddToScheme(scheme)) if infrastructure.IsOpenShift() { utilruntime.Must(routev1.Install(scheme)) diff --git a/pkg/config/sync.go b/pkg/config/sync.go index 1faf0baa6..2cb12b275 100644 --- a/pkg/config/sync.go +++ b/pkg/config/sync.go @@ -284,6 +284,9 @@ func mergeConfig(from, to *controller.OperatorConfiguration) { if from.Routing.ClusterHostSuffix != "" { to.Routing.ClusterHostSuffix = from.Routing.ClusterHostSuffix } + if from.Routing.GatewayRef != nil { + to.Routing.GatewayRef = from.Routing.GatewayRef.DeepCopy() + } if from.Routing.ProxyConfig != nil { if to.Routing.ProxyConfig == nil { to.Routing.ProxyConfig = &controller.Proxy{} diff --git a/pkg/provision/sync/diff.go b/pkg/provision/sync/diff.go index 69307489a..d2182de5d 100644 --- a/pkg/provision/sync/diff.go +++ b/pkg/provision/sync/diff.go @@ -30,6 +30,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/pointer" crclient "sigs.k8s.io/controller-runtime/pkg/client" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" ) @@ -52,6 +53,7 @@ var diffFuncs = map[reflect.Type]diffFunc{ reflect.TypeOf(networkingv1.Ingress{}): allDiffFuncs(metadataDiffFunc, basicDiffFunc(ingressDiffOpts)), reflect.TypeOf(networkingv1.NetworkPolicy{}): allDiffFuncs(metadataDiffFunc, basicDiffFunc(networkPolicyDiffOpts)), reflect.TypeOf(routev1.Route{}): allDiffFuncs(metadataDiffFunc, basicDiffFunc(routeDiffOpts)), + reflect.TypeOf(gwapiv1.HTTPRoute{}): allDiffFuncs(metadataDiffFunc, basicDiffFunc(httpRouteDiffOpts)), } // basicDiffFunc returns a diffFunc that specifies an object needs an update if cmp.Equal fails diff --git a/pkg/provision/sync/diffopts.go b/pkg/provision/sync/diffopts.go index a1a751336..cb0e5aa51 100644 --- a/pkg/provision/sync/diffopts.go +++ b/pkg/provision/sync/diffopts.go @@ -25,6 +25,7 @@ import ( networkingv1 "k8s.io/api/networking/v1" rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" ) var roleDiffOpts = cmp.Options{ @@ -98,6 +99,13 @@ var networkPolicyDiffOpts = cmp.Options{ cmpopts.IgnoreFields(networkingv1.NetworkPolicy{}, "TypeMeta", "ObjectMeta"), } +var httpRouteDiffOpts = cmp.Options{ + cmpopts.IgnoreFields(gwapiv1.HTTPRoute{}, "TypeMeta", "ObjectMeta", "Status"), + cmpopts.IgnoreFields(gwapiv1.BackendRef{}, "Weight"), + cmpopts.IgnoreFields(gwapiv1.BackendObjectReference{}, "Group", "Kind", "Namespace"), + cmpopts.IgnoreFields(gwapiv1.ParentReference{}, "Group", "Kind", "Namespace"), +} + func getNameFromEnvFrom(source corev1.EnvFromSource) string { switch { case source.ConfigMapRef != nil: From 89959f815c0b7220edf8f528deea016ae3f7b1fe Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Thu, 18 Jun 2026 15:09:11 -0400 Subject: [PATCH 3/8] feat: implement gateway-api routing class and fix controller readiness stalls Signed-off-by: Badre Tejado-Imam --- .../devworkspacerouting_controller.go | 12 ++++--- .../devworkspacerouting/sync_httproutes.go | 1 + ...evfile.io_devworkspaceoperatorconfigs.yaml | 26 +++++++++++++++ ...kspace-operator.clusterserviceversion.yaml | 6 ++++ deploy/deployment/kubernetes/combined.yaml | 32 +++++++++++++++++++ ...workspace-controller-role.ClusterRole.yaml | 6 ++++ ...r.devfile.io.CustomResourceDefinition.yaml | 26 +++++++++++++++ deploy/deployment/openshift/combined.yaml | 32 +++++++++++++++++++ ...workspace-controller-role.ClusterRole.yaml | 6 ++++ ...r.devfile.io.CustomResourceDefinition.yaml | 26 +++++++++++++++ 10 files changed, 169 insertions(+), 4 deletions(-) diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index 2e964f374..acb83ec4e 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -301,13 +301,13 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. if err != nil { failError := &sync.UnrecoverableSyncError{} if errors.As(err, &failError) { - return reconcile.Result{}, r.markRoutingFailed(instance, err.Error()) + return reconcile.Result{}, r.markRoutingFailed(ctx, instance, err.Error()) } reqLogger.Error(err, "Error syncing HTTPRoutes") - return reconcile.Result{Requeue: true}, r.reconcileStatus(instance, nil, nil, false, "Preparing HTTPRoutes") + return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") } else if !httpRoutesInSync { reqLogger.Info("HTTPRoutes not in sync") - return reconcile.Result{Requeue: true}, r.reconcileStatus(instance, nil, nil, false, "Preparing HTTPRoutes") + return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") } clusterRoutingObj.HTTPRoutes = clusterHTTPRoutes } @@ -318,6 +318,11 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. return reconcile.Result{}, r.markRoutingFailed(ctx, instance, fmt.Sprintf("Could not get exposed endpoints for DevWorkspace: %s", err)) } + if !endpointsAreReady { + reqLogger.Info("Endpoints not ready, requeuing to check HTTPRoute status") + return reconcile.Result{RequeueAfter: 3 * time.Second}, r.reconcileStatus(ctx, instance, nil, nil, false, "Waiting for HTTPRoute endpoints to be ready") + } + return reconcile.Result{}, r.reconcileStatus(ctx, instance, &routingObjects, exposedEndpoints, endpointsAreReady, "") } @@ -328,7 +333,6 @@ func workspaceName(routing *controllerv1alpha1.DevWorkspaceRouting) string { return "" } return owner.Name -} // setFinalizer ensures a finalizer is set on a devWorkspaceRouting instance; no-op if finalizer is already present. func (r *DevWorkspaceRoutingReconciler) setFinalizer(reqLogger logr.Logger, solver solvers.RoutingSolver, m *controllerv1alpha1.DevWorkspaceRouting) error { diff --git a/controllers/controller/devworkspacerouting/sync_httproutes.go b/controllers/controller/devworkspacerouting/sync_httproutes.go index 1ae360622..d67c0381e 100644 --- a/controllers/controller/devworkspacerouting/sync_httproutes.go +++ b/controllers/controller/devworkspacerouting/sync_httproutes.go @@ -59,6 +59,7 @@ func (r *DevWorkspaceRoutingReconciler) syncHTTPRoutes(routing *controllerv1alph case nil: break case *sync.NotInSyncError: + clusterAPI.Logger.Info(t.Error()) httpRoutesInSync = false continue case *sync.UnrecoverableSyncError: diff --git a/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml b/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml index b10e06d94..2e973843e 100644 --- a/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml +++ b/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml @@ -57,6 +57,32 @@ spec: specifies an empty `.spec.routingClass`. Supported routingClasses can be defined in other controllers. If not specified, the default value of "basic" is used. type: string + gatewayRef: + description: |- + GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + should attach to when using the 'gateway-api' routing class. This field is required + when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + properties: + gatewayClassName: + default: nginx + description: |- + GatewayClassName is the name of the GatewayClass to use. + This is used for validation and informational purposes. + Defaults to "nginx" if not specified. + type: string + name: + description: Name is the name of the Gateway resource + type: string + namespace: + description: |- + Namespace is the namespace of the Gateway resource. + If not specified, HTTPRoutes will reference a Gateway in the same namespace + as the DevWorkspace. + type: string + required: + - name + type: object proxyConfig: description: |- ProxyConfig defines the proxy settings that should be used for all DevWorkspaces. diff --git a/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml b/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml index a18cebde0..e95dc5f37 100644 --- a/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml +++ b/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml @@ -264,6 +264,12 @@ spec: - create - get - update + - apiGroups: + - gateway.networking.k8s.io + resources: + - httproutes + verbs: + - '*' - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/kubernetes/combined.yaml b/deploy/deployment/kubernetes/combined.yaml index 62ee23a21..1b6057da6 100644 --- a/deploy/deployment/kubernetes/combined.yaml +++ b/deploy/deployment/kubernetes/combined.yaml @@ -58,6 +58,32 @@ spec: specifies an empty `.spec.routingClass`. Supported routingClasses can be defined in other controllers. If not specified, the default value of "basic" is used. type: string + gatewayRef: + description: |- + GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + should attach to when using the 'gateway-api' routing class. This field is required + when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + properties: + gatewayClassName: + default: nginx + description: |- + GatewayClassName is the name of the GatewayClass to use. + This is used for validation and informational purposes. + Defaults to "nginx" if not specified. + type: string + name: + description: Name is the name of the Gateway resource + type: string + namespace: + description: |- + Namespace is the namespace of the Gateway resource. + If not specified, HTTPRoutes will reference a Gateway in the same namespace + as the DevWorkspace. + type: string + required: + - name + type: object proxyConfig: description: |- ProxyConfig defines the proxy settings that should be used for all DevWorkspaces. @@ -29566,6 +29592,12 @@ rules: - create - get - update +- apiGroups: + - gateway.networking.k8s.io + resources: + - httproutes + verbs: + - '*' - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml b/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml index 22d965689..4286d70bb 100644 --- a/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml +++ b/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml @@ -184,6 +184,12 @@ rules: - create - get - update +- apiGroups: + - gateway.networking.k8s.io + resources: + - httproutes + verbs: + - '*' - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml b/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml index 27217b3fe..eb3abba56 100644 --- a/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml +++ b/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml @@ -58,6 +58,32 @@ spec: specifies an empty `.spec.routingClass`. Supported routingClasses can be defined in other controllers. If not specified, the default value of "basic" is used. type: string + gatewayRef: + description: |- + GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + should attach to when using the 'gateway-api' routing class. This field is required + when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + properties: + gatewayClassName: + default: nginx + description: |- + GatewayClassName is the name of the GatewayClass to use. + This is used for validation and informational purposes. + Defaults to "nginx" if not specified. + type: string + name: + description: Name is the name of the Gateway resource + type: string + namespace: + description: |- + Namespace is the namespace of the Gateway resource. + If not specified, HTTPRoutes will reference a Gateway in the same namespace + as the DevWorkspace. + type: string + required: + - name + type: object proxyConfig: description: |- ProxyConfig defines the proxy settings that should be used for all DevWorkspaces. diff --git a/deploy/deployment/openshift/combined.yaml b/deploy/deployment/openshift/combined.yaml index 6b961bdae..534bf793a 100644 --- a/deploy/deployment/openshift/combined.yaml +++ b/deploy/deployment/openshift/combined.yaml @@ -58,6 +58,32 @@ spec: specifies an empty `.spec.routingClass`. Supported routingClasses can be defined in other controllers. If not specified, the default value of "basic" is used. type: string + gatewayRef: + description: |- + GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + should attach to when using the 'gateway-api' routing class. This field is required + when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + properties: + gatewayClassName: + default: nginx + description: |- + GatewayClassName is the name of the GatewayClass to use. + This is used for validation and informational purposes. + Defaults to "nginx" if not specified. + type: string + name: + description: Name is the name of the Gateway resource + type: string + namespace: + description: |- + Namespace is the namespace of the Gateway resource. + If not specified, HTTPRoutes will reference a Gateway in the same namespace + as the DevWorkspace. + type: string + required: + - name + type: object proxyConfig: description: |- ProxyConfig defines the proxy settings that should be used for all DevWorkspaces. @@ -29566,6 +29592,12 @@ rules: - create - get - update +- apiGroups: + - gateway.networking.k8s.io + resources: + - httproutes + verbs: + - '*' - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml b/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml index 22d965689..4286d70bb 100644 --- a/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml +++ b/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml @@ -184,6 +184,12 @@ rules: - create - get - update +- apiGroups: + - gateway.networking.k8s.io + resources: + - httproutes + verbs: + - '*' - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml b/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml index 27217b3fe..eb3abba56 100644 --- a/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml +++ b/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml @@ -58,6 +58,32 @@ spec: specifies an empty `.spec.routingClass`. Supported routingClasses can be defined in other controllers. If not specified, the default value of "basic" is used. type: string + gatewayRef: + description: |- + GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes + should attach to when using the 'gateway-api' routing class. This field is required + when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned + by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + properties: + gatewayClassName: + default: nginx + description: |- + GatewayClassName is the name of the GatewayClass to use. + This is used for validation and informational purposes. + Defaults to "nginx" if not specified. + type: string + name: + description: Name is the name of the Gateway resource + type: string + namespace: + description: |- + Namespace is the namespace of the Gateway resource. + If not specified, HTTPRoutes will reference a Gateway in the same namespace + as the DevWorkspace. + type: string + required: + - name + type: object proxyConfig: description: |- ProxyConfig defines the proxy settings that should be used for all DevWorkspaces. From 1aae48a14b02b30a222275f2dbae8de927155ca5 Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Tue, 4 Aug 2026 12:33:02 -0400 Subject: [PATCH 4/8] fix: address PR review feedback for Gateway API routing - Remove unused GatewayClassName field from GatewayReference struct - Add MinLength/MaxLength validation markers on GatewayReference fields - Gate HTTPRoute watch and cache behind Gateway API CRD availability using infrastructure detection pattern (IsGatewayAPIInstalled) - Scope httproutes RBAC from wildcard to explicit verbs - Make endpoint readiness log/status messages generic - Extract httpRouteRequestTimeout constant for HTTPRoute timeout - Reuse getURLForEndpoint for HTTPRoute URL construction Assisted-by: Claude Opus 4.6 Signed-off-by: Badre Tejado-Imam Co-Authored-By: Claude Opus 4.6 Signed-off-by: Badre Tejado-Imam --- .../devworkspaceoperatorconfig_types.go | 10 ++--- .../devworkspacerouting_controller.go | 12 ++--- .../devworkspacerouting_controller_test.go | 5 +-- .../solvers/gateway_api_solver.go | 15 +++++-- .../devworkspacerouting/suite_test.go | 1 + ...evfile.io_devworkspaceoperatorconfigs.yaml | 11 ++--- ...kspace-operator.clusterserviceversion.yaml | 8 +++- deploy/deployment/kubernetes/combined.yaml | 19 ++++---- ...workspace-controller-role.ClusterRole.yaml | 8 +++- ...r.devfile.io.CustomResourceDefinition.yaml | 11 ++--- deploy/deployment/openshift/combined.yaml | 19 ++++---- ...workspace-controller-role.ClusterRole.yaml | 8 +++- ...r.devfile.io.CustomResourceDefinition.yaml | 11 ++--- deploy/templates/components/rbac/role.yaml | 8 +++- ...evfile.io_devworkspaceoperatorconfigs.yaml | 11 ++--- pkg/cache/cache.go | 4 ++ pkg/infrastructure/cluster.go | 44 +++++++++++++------ 17 files changed, 125 insertions(+), 80 deletions(-) diff --git a/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go b/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go index 9a845d1ca..7a7963a1f 100644 --- a/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go +++ b/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go @@ -125,18 +125,16 @@ type BackupCronJobConfig struct { type GatewayReference struct { // Name is the name of the Gateway resource // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 Name string `json:"name"` // Namespace is the namespace of the Gateway resource. // If not specified, HTTPRoutes will reference a Gateway in the same namespace // as the DevWorkspace. // +kubebuilder:validation:Optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 Namespace *string `json:"namespace,omitempty"` - // GatewayClassName is the name of the GatewayClass to use. - // This is used for validation and informational purposes. - // Defaults to "nginx" if not specified. - // +kubebuilder:validation:Optional - // +kubebuilder:default:="nginx" - GatewayClassName string `json:"gatewayClassName,omitempty"` } type RoutingConfig struct { diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index acb83ec4e..27dbd0a6d 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -72,7 +72,7 @@ type DevWorkspaceRoutingReconciler struct { // +kubebuilder:rbac:groups=route.openshift.io,resources=routes,verbs=* // +kubebuidler:rbac:groups=route.openshift.io,resources=routes/status,verbs=get,list,watch // +kubebuilder:rbac:groups=route.openshift.io,resources=routes/custom-host,verbs=create -// +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=httproutes,verbs=* +// +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=httproutes,verbs=get;list;watch;create;update;patch;delete func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { reqLogger := r.Log.WithValues("Request.Namespace", req.Namespace, "Request.Name", req.Name) @@ -319,8 +319,8 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. } if !endpointsAreReady { - reqLogger.Info("Endpoints not ready, requeuing to check HTTPRoute status") - return reconcile.Result{RequeueAfter: 3 * time.Second}, r.reconcileStatus(ctx, instance, nil, nil, false, "Waiting for HTTPRoute endpoints to be ready") + reqLogger.Info("Endpoints not ready, requeuing") + return reconcile.Result{RequeueAfter: 3 * time.Second}, r.reconcileStatus(ctx, instance, nil, nil, false, "Waiting for endpoints to be ready") } return reconcile.Result{}, r.reconcileStatus(ctx, instance, &routingObjects, exposedEndpoints, endpointsAreReady, "") @@ -459,11 +459,13 @@ func (r *DevWorkspaceRoutingReconciler) SetupWithManager(mgr ctrl.Manager) error }). For(&controllerv1alpha1.DevWorkspaceRouting{}). Owns(&corev1.Service{}). - Owns(&networkingv1.Ingress{}). - Owns(&gwapiv1.HTTPRoute{}) + Owns(&networkingv1.Ingress{}) if infrastructure.IsOpenShift() { bld.Owns(&routeV1.Route{}) } + if infrastructure.IsGatewayAPIInstalled() { + bld.Owns(&gwapiv1.HTTPRoute{}) + } if r.SolverGetter == nil { return NoSolversEnabled } diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go index 333c07fa7..ee0684ed3 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go @@ -432,9 +432,8 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { ClusterHostSuffix: "test-environment-cluster-suffix", DefaultRoutingClass: "gateway-api", GatewayRef: &controllerv1alpha1.GatewayReference{ - Name: gatewayName, - Namespace: &gatewayRefNamespace, - GatewayClassName: "nginx", + Name: gatewayName, + Namespace: &gatewayRefNamespace, }, } config.SetGlobalConfigForTesting(dwoc) diff --git a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go index 882beb219..c174e3a54 100644 --- a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go +++ b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go @@ -25,6 +25,9 @@ import ( gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" ) +// Long-running workspace sessions need generous timeouts +const httpRouteRequestTimeout = gwapiv1.Duration("10h") + // GatewayAPISolver exposes endpoints using Kubernetes Gateway API HTTPRoutes // HTTPRoutes are attached to a Gateway specified in the operator configuration type GatewayAPISolver struct{} @@ -208,8 +211,7 @@ func (s *GatewayAPISolver) createHTTPSBackendRoute( pathPrefix := gwapiv1.PathMatchPathPrefix pathValue := "/" - // 10 hour timeout (matching ingress2gateway output and long-running workspace sessions) - requestTimeout := gwapiv1.Duration("10h") + requestTimeout := httpRouteRequestTimeout group := gwapiv1.Group(gwapiv1.GroupVersion.Group) kind := gwapiv1.Kind("Gateway") @@ -307,8 +309,13 @@ func getExposedEndpointsFromHTTPRoutes( if len(httpRoute.Spec.Rules) > 0 && len(httpRoute.Spec.Rules[0].BackendRefs) > 0 { if len(httpRoute.Spec.Hostnames) > 0 { hostname := string(httpRoute.Spec.Hostnames[0]) - // Use HTTPS scheme - url = fmt.Sprintf("https://%s%s", hostname, endpoint.Path) + secureEndpoint := endpoint + secureEndpoint.Secure = true + var urlErr error + url, urlErr = getURLForEndpoint(secureEndpoint, hostname, "", true) + if urlErr != nil { + return nil, false, urlErr + } break } } diff --git a/controllers/controller/devworkspacerouting/suite_test.go b/controllers/controller/devworkspacerouting/suite_test.go index 1b633b9f7..6803c0659 100644 --- a/controllers/controller/devworkspacerouting/suite_test.go +++ b/controllers/controller/devworkspacerouting/suite_test.go @@ -102,6 +102,7 @@ var _ = BeforeSuite(func() { Expect(cfg).NotTo(BeNil()) infrastructure.InitializeForTesting(infrastructure.OpenShiftv4) + infrastructure.SetGatewayAPIInstalledForTesting(true) config.SetGlobalConfigForTesting(testControllerCfg) err = controllerv1alpha1.AddToScheme(scheme.Scheme) diff --git a/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml b/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml index 2e973843e..e4b576520 100644 --- a/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml +++ b/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml @@ -64,21 +64,18 @@ spec: when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned by the cluster administrator or Che Operator before workspaces can use Gateway API routing. properties: - gatewayClassName: - default: nginx - description: |- - GatewayClassName is the name of the GatewayClass to use. - This is used for validation and informational purposes. - Defaults to "nginx" if not specified. - type: string name: description: Name is the name of the Gateway resource + maxLength: 253 + minLength: 1 type: string namespace: description: |- Namespace is the namespace of the Gateway resource. If not specified, HTTPRoutes will reference a Gateway in the same namespace as the DevWorkspace. + maxLength: 63 + minLength: 1 type: string required: - name diff --git a/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml b/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml index e95dc5f37..66d9a0b64 100644 --- a/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml +++ b/deploy/bundle/manifests/devworkspace-operator.clusterserviceversion.yaml @@ -269,7 +269,13 @@ spec: resources: - httproutes verbs: - - '*' + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/kubernetes/combined.yaml b/deploy/deployment/kubernetes/combined.yaml index 1b6057da6..56eb76e18 100644 --- a/deploy/deployment/kubernetes/combined.yaml +++ b/deploy/deployment/kubernetes/combined.yaml @@ -65,21 +65,18 @@ spec: when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned by the cluster administrator or Che Operator before workspaces can use Gateway API routing. properties: - gatewayClassName: - default: nginx - description: |- - GatewayClassName is the name of the GatewayClass to use. - This is used for validation and informational purposes. - Defaults to "nginx" if not specified. - type: string name: description: Name is the name of the Gateway resource + maxLength: 253 + minLength: 1 type: string namespace: description: |- Namespace is the namespace of the Gateway resource. If not specified, HTTPRoutes will reference a Gateway in the same namespace as the DevWorkspace. + maxLength: 63 + minLength: 1 type: string required: - name @@ -29597,7 +29594,13 @@ rules: resources: - httproutes verbs: - - '*' + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml b/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml index 4286d70bb..db815a16a 100644 --- a/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml +++ b/deploy/deployment/kubernetes/objects/devworkspace-controller-role.ClusterRole.yaml @@ -189,7 +189,13 @@ rules: resources: - httproutes verbs: - - '*' + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml b/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml index eb3abba56..81913ccdd 100644 --- a/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml +++ b/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml @@ -65,21 +65,18 @@ spec: when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned by the cluster administrator or Che Operator before workspaces can use Gateway API routing. properties: - gatewayClassName: - default: nginx - description: |- - GatewayClassName is the name of the GatewayClass to use. - This is used for validation and informational purposes. - Defaults to "nginx" if not specified. - type: string name: description: Name is the name of the Gateway resource + maxLength: 253 + minLength: 1 type: string namespace: description: |- Namespace is the namespace of the Gateway resource. If not specified, HTTPRoutes will reference a Gateway in the same namespace as the DevWorkspace. + maxLength: 63 + minLength: 1 type: string required: - name diff --git a/deploy/deployment/openshift/combined.yaml b/deploy/deployment/openshift/combined.yaml index 534bf793a..e2dfac5ed 100644 --- a/deploy/deployment/openshift/combined.yaml +++ b/deploy/deployment/openshift/combined.yaml @@ -65,21 +65,18 @@ spec: when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned by the cluster administrator or Che Operator before workspaces can use Gateway API routing. properties: - gatewayClassName: - default: nginx - description: |- - GatewayClassName is the name of the GatewayClass to use. - This is used for validation and informational purposes. - Defaults to "nginx" if not specified. - type: string name: description: Name is the name of the Gateway resource + maxLength: 253 + minLength: 1 type: string namespace: description: |- Namespace is the namespace of the Gateway resource. If not specified, HTTPRoutes will reference a Gateway in the same namespace as the DevWorkspace. + maxLength: 63 + minLength: 1 type: string required: - name @@ -29597,7 +29594,13 @@ rules: resources: - httproutes verbs: - - '*' + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml b/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml index 4286d70bb..db815a16a 100644 --- a/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml +++ b/deploy/deployment/openshift/objects/devworkspace-controller-role.ClusterRole.yaml @@ -189,7 +189,13 @@ rules: resources: - httproutes verbs: - - '*' + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - image.openshift.io resources: diff --git a/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml b/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml index eb3abba56..81913ccdd 100644 --- a/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml +++ b/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml @@ -65,21 +65,18 @@ spec: when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned by the cluster administrator or Che Operator before workspaces can use Gateway API routing. properties: - gatewayClassName: - default: nginx - description: |- - GatewayClassName is the name of the GatewayClass to use. - This is used for validation and informational purposes. - Defaults to "nginx" if not specified. - type: string name: description: Name is the name of the Gateway resource + maxLength: 253 + minLength: 1 type: string namespace: description: |- Namespace is the namespace of the Gateway resource. If not specified, HTTPRoutes will reference a Gateway in the same namespace as the DevWorkspace. + maxLength: 63 + minLength: 1 type: string required: - name diff --git a/deploy/templates/components/rbac/role.yaml b/deploy/templates/components/rbac/role.yaml index 57dc31600..e31039fbd 100644 --- a/deploy/templates/components/rbac/role.yaml +++ b/deploy/templates/components/rbac/role.yaml @@ -187,7 +187,13 @@ rules: resources: - httproutes verbs: - - '*' + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - image.openshift.io resources: diff --git a/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml b/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml index f316eb757..a243a7287 100644 --- a/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml +++ b/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml @@ -63,21 +63,18 @@ spec: when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned by the cluster administrator or Che Operator before workspaces can use Gateway API routing. properties: - gatewayClassName: - default: nginx - description: |- - GatewayClassName is the name of the GatewayClass to use. - This is used for validation and informational purposes. - Defaults to "nginx" if not specified. - type: string name: description: Name is the name of the Gateway resource + maxLength: 253 + minLength: 1 type: string namespace: description: |- Namespace is the namespace of the Gateway resource. If not specified, HTTPRoutes will reference a Gateway in the same namespace as the DevWorkspace. + maxLength: 63 + minLength: 1 type: string required: - name diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index aa77c9bdb..dbc477ea0 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -29,6 +29,7 @@ import ( rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/labels" "sigs.k8s.io/controller-runtime/pkg/cache" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" ) // GetCacheFunc returns a new cache function that restricts the cluster items we store in the manager's @@ -100,6 +101,9 @@ func GetCacheFunc() (cache.NewCacheFunc, error) { if infrastructure.IsOpenShift() { selectors[&routev1.Route{}] = cache.ByObject{Label: devworkspaceObjectSelector} } + if infrastructure.IsGatewayAPIInstalled() { + selectors[&gwapiv1.HTTPRoute{}] = cache.ByObject{Label: devworkspaceObjectSelector} + } return func(config *rest.Config, opts cache.Options) (cache.Cache, error) { opts.ByObject = selectors diff --git a/pkg/infrastructure/cluster.go b/pkg/infrastructure/cluster.go index 844343536..6c6ab8229 100644 --- a/pkg/infrastructure/cluster.go +++ b/pkg/infrastructure/cluster.go @@ -35,21 +35,23 @@ const ( var ( // current is the infrastructure that we're currently running on. - current Type - initialized = false + current Type + initialized = false + isGatewayAPIInstalled bool ) // Initialize attempts to determine the type of cluster its currently running on (OpenShift or Kubernetes). This function // *must* be called before others; otherwise the call will panic. func Initialize() error { - var err error - current, err = detect() + infraType, apiGroups, err := detect() if err != nil { return err } - if current == Unsupported { + if infraType == Unsupported { return fmt.Errorf("running on unsupported cluster") } + current = infraType + isGatewayAPIInstalled = findAPIGroup(apiGroups, "gateway.networking.k8s.io") != nil initialized = true return nil } @@ -72,26 +74,40 @@ func IsOpenShift() bool { return current == OpenShiftv4 } -func detect() (Type, error) { +// IsGatewayAPIInstalled returns true if the Gateway API CRDs are installed on the cluster. +func IsGatewayAPIInstalled() bool { + if !initialized { + panic("Attempting to determine information about the cluster without initializing first") + } + return isGatewayAPIInstalled +} + +// SetGatewayAPIInstalledForTesting is used to mock Gateway API availability in testing code. +func SetGatewayAPIInstalledForTesting(installed bool) { + isGatewayAPIInstalled = installed +} + +func detect() (Type, []metav1.APIGroup, error) { kubeCfg, err := config.GetConfig() if err != nil { - return Unsupported, fmt.Errorf("could not get kube config: %w", err) + return Unsupported, nil, fmt.Errorf("could not get kube config: %w", err) } discoveryClient, err := discovery.NewDiscoveryClientForConfig(kubeCfg) if err != nil { - return Unsupported, fmt.Errorf("could not get discovery client: %w", err) + return Unsupported, nil, fmt.Errorf("could not get discovery client: %w", err) } apiList, err := discoveryClient.ServerGroups() if err != nil { - return Unsupported, fmt.Errorf("could not read API groups: %w", err) + return Unsupported, nil, fmt.Errorf("could not read API groups: %w", err) } - if findAPIGroup(apiList.Groups, "route.openshift.io") == nil { - return Kubernetes, nil + groups := apiList.Groups + if findAPIGroup(groups, "route.openshift.io") == nil { + return Kubernetes, groups, nil } else { - if findAPIGroup(apiList.Groups, "config.openshift.io") == nil { - return Unsupported, nil + if findAPIGroup(groups, "config.openshift.io") == nil { + return Unsupported, groups, nil } else { - return OpenShiftv4, nil + return OpenShiftv4, groups, nil } } } From 40a9386d0588eda48e27f6552c8a134daf729e11 Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Tue, 8 Sep 2026 12:22:11 -0400 Subject: [PATCH 5/8] fix: address PR review feedback for Gateway API routing (round 2) - Call syncHTTPRoutes unconditionally so stale HTTPRoutes get cleaned up when desired list becomes empty - Stop ignoring ParentReference.Namespace in diff opts so gateway namespace changes propagate to existing HTTPRoutes - Check IsGatewayAPIInstalled() before returning Gateway API solver for clear upfront error when CRDs are not installed - Fix annotation ordering in solver: user annotations first, controller annotation last, matching basic solver pattern - Add GatewayRef details to GetCurrentConfigString output - Replace deprecated gwapiv1.AddToScheme with gwapiv1.Install - Remove redundant RequeueAfter on endpoints-not-ready path since watch-based triggers handle reconciliation - Remove logging on NotInSyncError to match other sync files - Remove Eclipse Che reference from GatewayRef doc comment - Add RFC 1123 pattern validation on GatewayReference Name and Namespace - Test improvements: use routing class constant, add ExposedEndpoints and hostname assertions, add nil-pointer guards, make deleteHTTPRoute idempotent, add gateway-api failure test cases Assisted-by: Claude Code Co-Authored-By: Claude Opus 4.6 Signed-off-by: Badre Tejado-Imam --- .../devworkspaceoperatorconfig_types.go | 4 +- .../devworkspacerouting_controller.go | 30 ++++---- .../devworkspacerouting_controller_test.go | 70 ++++++++++++++++++- .../solvers/gateway_api_solver.go | 15 ++-- .../devworkspacerouting/solvers/solver.go | 3 + .../devworkspacerouting/suite_test.go | 2 +- .../devworkspacerouting/sync_httproutes.go | 1 - .../devworkspacerouting/util_test.go | 14 ++-- ...evfile.io_devworkspaceoperatorconfigs.yaml | 4 +- deploy/deployment/kubernetes/combined.yaml | 4 +- ...r.devfile.io.CustomResourceDefinition.yaml | 4 +- deploy/deployment/openshift/combined.yaml | 4 +- ...r.devfile.io.CustomResourceDefinition.yaml | 4 +- ...evfile.io_devworkspaceoperatorconfigs.yaml | 4 +- main.go | 2 +- pkg/config/sync.go | 6 ++ pkg/provision/sync/diffopts.go | 2 +- 17 files changed, 131 insertions(+), 42 deletions(-) diff --git a/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go b/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go index 7a7963a1f..4e43db81e 100644 --- a/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go +++ b/apis/controller/v1alpha1/devworkspaceoperatorconfig_types.go @@ -127,6 +127,7 @@ type GatewayReference struct { // +kubebuilder:validation:Required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` Name string `json:"name"` // Namespace is the namespace of the Gateway resource. // If not specified, HTTPRoutes will reference a Gateway in the same namespace @@ -134,6 +135,7 @@ type GatewayReference struct { // +kubebuilder:validation:Optional // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$` Namespace *string `json:"namespace,omitempty"` } @@ -165,7 +167,7 @@ type RoutingConfig struct { // GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes // should attach to when using the 'gateway-api' routing class. This field is required // when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - // by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + // by the cluster administrator before workspaces can use Gateway API routing. // +kubebuilder:validation:Optional GatewayRef *GatewayReference `json:"gatewayRef,omitempty"` } diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index 27dbd0a6d..ed52cc173 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -295,22 +295,20 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. clusterRoutingObj.Ingresses = clusterIngresses } - // Sync HTTPRoutes if using gateway-api routing class - if len(httpRoutes) > 0 { - httpRoutesInSync, clusterHTTPRoutes, err := r.syncHTTPRoutes(instance, httpRoutes) - if err != nil { - failError := &sync.UnrecoverableSyncError{} - if errors.As(err, &failError) { - return reconcile.Result{}, r.markRoutingFailed(ctx, instance, err.Error()) - } - reqLogger.Error(err, "Error syncing HTTPRoutes") - return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") - } else if !httpRoutesInSync { - reqLogger.Info("HTTPRoutes not in sync") - return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") + // Sync HTTPRoutes (always, so stale HTTPRoutes get cleaned up even when 0 are desired) + httpRoutesInSync, clusterHTTPRoutes, err := r.syncHTTPRoutes(instance, httpRoutes) + if err != nil { + failError := &sync.UnrecoverableSyncError{} + if errors.As(err, &failError) { + return reconcile.Result{}, r.markRoutingFailed(ctx, instance, err.Error()) } - clusterRoutingObj.HTTPRoutes = clusterHTTPRoutes + reqLogger.Error(err, "Error syncing HTTPRoutes") + return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") + } else if !httpRoutesInSync { + reqLogger.Info("HTTPRoutes not in sync") + return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") } + clusterRoutingObj.HTTPRoutes = clusterHTTPRoutes exposedEndpoints, endpointsAreReady, err := solver.GetExposedEndpoints(instance.Spec.Endpoints, clusterRoutingObj) if err != nil { @@ -319,8 +317,8 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. } if !endpointsAreReady { - reqLogger.Info("Endpoints not ready, requeuing") - return reconcile.Result{RequeueAfter: 3 * time.Second}, r.reconcileStatus(ctx, instance, nil, nil, false, "Waiting for endpoints to be ready") + reqLogger.Info("Endpoints not ready") + return reconcile.Result{}, r.reconcileStatus(ctx, instance, nil, nil, false, "Waiting for endpoints to be ready") } return reconcile.Result{}, r.reconcileStatus(ctx, instance, &routingObjects, exposedEndpoints, endpointsAreReady, "") diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go index ee0684ed3..47fe9a79f 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller_test.go @@ -430,7 +430,7 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { dwoc := testControllerCfg.DeepCopy() dwoc.Routing = &controllerv1alpha1.RoutingConfig{ ClusterHostSuffix: "test-environment-cluster-suffix", - DefaultRoutingClass: "gateway-api", + DefaultRoutingClass: string(controllerv1alpha1.DevWorkspaceRoutingGatewayAPI), GatewayRef: &controllerv1alpha1.GatewayReference{ Name: gatewayName, Namespace: &gatewayRefNamespace, @@ -512,6 +512,9 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { }, timeout, interval).Should(Equal(controllerv1alpha1.RoutingReady), "DevWorkspaceRouting should have Ready phase") Expect(createdDWR.Status.Message).ShouldNot(BeNil(), "Status message should be set for preparing DevWorkspaceRoutings") Expect(createdDWR.Status.Message).Should(Equal("DevWorkspaceRouting prepared"), "Status message should indicate that the DevWorkspaceRouting is prepared") + + By("Checking ExposedEndpoints are set") + Expect(createdDWR.Status.ExposedEndpoints).ShouldNot(BeEmpty(), "ExposedEndpoints should be set when routing is ready") }) It("Creates services", func() { @@ -578,11 +581,17 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { Expect(createdHTTPRoute.ObjectMeta.Annotations).Should(HaveKeyWithValue(constants.DevWorkspaceEndpointNameAnnotation, exposedEndPointName), "HTTPRoute should have endpoint name annotation") Expect(createdHTTPRoute.ObjectMeta.Annotations).Should(HaveKeyWithValue(endpointAnnotationKey, endpointAnnotationValue), "HTTPRoute should have annotation from endpoint") + By("Checking HTTPRoute has correct hostnames") + expectedHostname := common.EndpointHostname("test-environment-cluster-suffix", testWorkspaceID, common.EndpointName(exposedEndPointName), exposedTargetPort) + Expect(createdHTTPRoute.Spec.Hostnames).Should(ContainElement(gwapiv1.Hostname(expectedHostname)), "HTTPRoute should have expected hostname") + By("Checking HTTPRoute has correct ParentRefs pointing to Gateway") Expect(len(createdHTTPRoute.Spec.ParentRefs)).Should(Equal(1), "HTTPRoute should have one parent reference") parentRef := createdHTTPRoute.Spec.ParentRefs[0] Expect(string(parentRef.Name)).Should(Equal(gatewayName), "HTTPRoute should reference the configured Gateway") + Expect(parentRef.Namespace).ShouldNot(BeNil(), "HTTPRoute parent reference should set the Gateway namespace") Expect(*parentRef.Namespace).Should(Equal(gwapiv1.Namespace(gatewayNamespace)), "HTTPRoute should reference Gateway in correct namespace") + Expect(parentRef.Port).ShouldNot(BeNil(), "HTTPRoute parent reference should set the Gateway listener port") Expect(*parentRef.Port).Should(Equal(gwapiv1.PortNumber(443)), "HTTPS HTTPRoute should reference port 443") By("Checking HTTPRoute points to service backend") @@ -598,11 +607,12 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { Expect(len(rule.BackendRefs)).Should(Equal(1), "HTTPRoute rule should have one backend reference") backendRef := rule.BackendRefs[0] Expect(string(backendRef.Name)).Should(Equal(createdService.Name), "HTTPRoute backend should reference the service") + Expect(backendRef.Port).ShouldNot(BeNil(), "HTTPRoute backend reference should set the port") Expect(*backendRef.Port).Should(Equal(gwapiv1.PortNumber(exposedTargetPort)), "HTTPRoute backend port should match endpoint target port") By("Checking HTTP redirect HTTPRoute is created") httpRedirectRoute := gwapiv1.HTTPRoute{} - httpRedirectRouteNamespacedName := namespacedName(common.RouteName(testWorkspaceID, exposedEndPointName)+"-http-redirect", testNamespace) + httpRedirectRouteNamespacedName := namespacedName(redirectRouteName(exposedEndPointName), testNamespace) Eventually(func() bool { err := k8sClient.Get(ctx, httpRedirectRouteNamespacedName, &httpRedirectRoute) return err == nil @@ -610,8 +620,10 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { Expect(httpRedirectRoute.Labels).Should(Equal(ExpectedLabels), "HTTP redirect HTTPRoute should contain DevWorkspace ID label") Expect(httpRedirectRoute.OwnerReferences).Should(ContainElement(expectedOwnerReference), "HTTP redirect HTTPRoute should be owned by DevWorkspaceRouting") + Expect(httpRedirectRoute.Spec.Hostnames).Should(ContainElement(gwapiv1.Hostname(expectedHostname)), "HTTP redirect HTTPRoute should have expected hostname") Expect(len(httpRedirectRoute.Spec.ParentRefs)).Should(Equal(1), "HTTP redirect HTTPRoute should have one parent reference") httpParentRef := httpRedirectRoute.Spec.ParentRefs[0] + Expect(httpParentRef.Port).ShouldNot(BeNil(), "HTTP redirect parent reference should set the port") Expect(*httpParentRef.Port).Should(Equal(gwapiv1.PortNumber(80)), "HTTP redirect HTTPRoute should reference port 80") By("Checking HTTP redirect HTTPRoute has redirect filter") @@ -623,7 +635,9 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { if filter.Type == gwapiv1.HTTPRouteFilterRequestRedirect { hasRedirectFilter = true Expect(filter.RequestRedirect).ShouldNot(BeNil(), "Redirect filter should have RequestRedirect configuration") + Expect(filter.RequestRedirect.Scheme).ShouldNot(BeNil(), "Redirect filter should set scheme") Expect(*filter.RequestRedirect.Scheme).Should(Equal("https"), "Redirect should be to HTTPS") + Expect(filter.RequestRedirect.StatusCode).ShouldNot(BeNil(), "Redirect filter should set status code") Expect(*filter.RequestRedirect.StatusCode).Should(Equal(301), "Redirect should use 301 status code") } } @@ -789,5 +803,57 @@ var _ = Describe("DevWorkspaceRouting Controller", func() { return updatedDWR.Status.Phase, nil }, timeout, interval).Should(Equal(controllerv1alpha1.RoutingFailed), "DevWorkspaceRouting should be in failed phase") }) + + It("Fails DevWorkspaceRouting with gateway-api routing class when Gateway API not installed", func() { + By("Setting Gateway API as not installed") + infrastructure.SetGatewayAPIInstalledForTesting(false) + defer infrastructure.SetGatewayAPIInstalledForTesting(true) + + By("Updating DevWorkspaceRouting to use gateway-api routing class") + Eventually(func() error { + createdDWR := getReadyDevWorkspaceRouting(devWorkspaceRoutingName) + createdDWR.Spec.RoutingClass = controllerv1alpha1.DevWorkspaceRoutingGatewayAPI + return k8sClient.Update(ctx, createdDWR) + }, timeout, interval).Should(Succeed(), "DevWorkspaceRouting routing class should be updated on cluster") + + By("Checking that the DevWorkspaceRouting has the failed status") + dwrNamespacedName := namespacedName(devWorkspaceRoutingName, testNamespace) + updatedDWR := &controllerv1alpha1.DevWorkspaceRouting{} + Eventually(func() (bool, error) { + err := k8sClient.Get(ctx, dwrNamespacedName, updatedDWR) + if err != nil { + return false, err + } + return updatedDWR.Status.Phase == controllerv1alpha1.RoutingFailed, nil + }, timeout, interval).Should(BeTrue(), "DevWorkspaceRouting should be in failed phase") + }) + + It("Fails DevWorkspaceRouting with gateway-api routing class when gatewayRef not configured", func() { + By("Configuring operator without gatewayRef") + dwoc := testControllerCfg.DeepCopy() + dwoc.Routing = &controllerv1alpha1.RoutingConfig{ + ClusterHostSuffix: "test-environment-cluster-suffix", + DefaultRoutingClass: string(controllerv1alpha1.DevWorkspaceRoutingGatewayAPI), + } + config.SetGlobalConfigForTesting(dwoc) + + By("Updating DevWorkspaceRouting to use gateway-api routing class") + Eventually(func() error { + createdDWR := getReadyDevWorkspaceRouting(devWorkspaceRoutingName) + createdDWR.Spec.RoutingClass = controllerv1alpha1.DevWorkspaceRoutingGatewayAPI + return k8sClient.Update(ctx, createdDWR) + }, timeout, interval).Should(Succeed(), "DevWorkspaceRouting routing class should be updated on cluster") + + By("Checking that the DevWorkspaceRouting has the failed status") + dwrNamespacedName := namespacedName(devWorkspaceRoutingName, testNamespace) + updatedDWR := &controllerv1alpha1.DevWorkspaceRouting{} + Eventually(func() (bool, error) { + err := k8sClient.Get(ctx, dwrNamespacedName, updatedDWR) + if err != nil { + return false, err + } + return updatedDWR.Status.Phase == controllerv1alpha1.RoutingFailed, nil + }, timeout, interval).Should(BeTrue(), "DevWorkspaceRouting should be in failed phase") + }) }) }) diff --git a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go index c174e3a54..0088191f5 100644 --- a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go +++ b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go @@ -17,12 +17,13 @@ package solvers import ( "fmt" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" + controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" "github.com/devfile/devworkspace-operator/pkg/common" "github.com/devfile/devworkspace-operator/pkg/config" "github.com/devfile/devworkspace-operator/pkg/constants" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" ) // Long-running workspace sessions need generous timeouts @@ -144,12 +145,11 @@ func (s *GatewayAPISolver) createHTTPRedirectRoute( namespace := gwapiv1.Namespace(gatewayNamespace) port := gwapiv1.PortNumber(80) - annotations := map[string]string{ - constants.DevWorkspaceEndpointNameAnnotation: endpoint.Name, - } + annotations := map[string]string{} for k, v := range endpoint.Annotations { annotations[k] = v } + annotations[constants.DevWorkspaceEndpointNameAnnotation] = endpoint.Name return gwapiv1.HTTPRoute{ ObjectMeta: metav1.ObjectMeta{ @@ -219,12 +219,11 @@ func (s *GatewayAPISolver) createHTTPSBackendRoute( httpsPort := gwapiv1.PortNumber(443) servicePort := gwapiv1.PortNumber(endpoint.TargetPort) - annotations := map[string]string{ - constants.DevWorkspaceEndpointNameAnnotation: endpoint.Name, - } + annotations := map[string]string{} for k, v := range endpoint.Annotations { annotations[k] = v } + annotations[constants.DevWorkspaceEndpointNameAnnotation] = endpoint.Name return gwapiv1.HTTPRoute{ ObjectMeta: metav1.ObjectMeta{ diff --git a/controllers/controller/devworkspacerouting/solvers/solver.go b/controllers/controller/devworkspacerouting/solvers/solver.go index 08e9cdacb..d468fcf2f 100644 --- a/controllers/controller/devworkspacerouting/solvers/solver.go +++ b/controllers/controller/devworkspacerouting/solvers/solver.go @@ -118,6 +118,9 @@ func (_ *SolverGetter) GetSolver(client client.Client, routingClass controllerv1 } return NewClusterSolver(client, true), nil case controllerv1alpha1.DevWorkspaceRoutingGatewayAPI: + if !infrastructure.IsGatewayAPIInstalled() { + return nil, fmt.Errorf("routing class %s requires Gateway API CRDs to be installed on the cluster", routingClass) + } return &GatewayAPISolver{}, nil default: return nil, RoutingNotSupported diff --git a/controllers/controller/devworkspacerouting/suite_test.go b/controllers/controller/devworkspacerouting/suite_test.go index 6803c0659..d1f60de37 100644 --- a/controllers/controller/devworkspacerouting/suite_test.go +++ b/controllers/controller/devworkspacerouting/suite_test.go @@ -113,7 +113,7 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) err = routev1.Install(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) - err = gwapiv1.AddToScheme(scheme.Scheme) + err = gwapiv1.Install(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) diff --git a/controllers/controller/devworkspacerouting/sync_httproutes.go b/controllers/controller/devworkspacerouting/sync_httproutes.go index d67c0381e..1ae360622 100644 --- a/controllers/controller/devworkspacerouting/sync_httproutes.go +++ b/controllers/controller/devworkspacerouting/sync_httproutes.go @@ -59,7 +59,6 @@ func (r *DevWorkspaceRoutingReconciler) syncHTTPRoutes(routing *controllerv1alph case nil: break case *sync.NotInSyncError: - clusterAPI.Logger.Info(t.Error()) httpRoutesInSync = false continue case *sync.UnrecoverableSyncError: diff --git a/controllers/controller/devworkspacerouting/util_test.go b/controllers/controller/devworkspacerouting/util_test.go index a6e5d436d..3d2d1b6e7 100644 --- a/controllers/controller/devworkspacerouting/util_test.go +++ b/controllers/controller/devworkspacerouting/util_test.go @@ -165,17 +165,21 @@ func deleteIngress(endpointName string, namespace string) { deleteObject(&createdIngress) } +func redirectRouteName(endpointName string) string { + return common.RouteName(testWorkspaceID, endpointName) + "-http-redirect" +} + func deleteHTTPRoute(endpointName string, namespace string, isRedirect bool) { createdHTTPRoute := gwapiv1.HTTPRoute{} routeName := common.RouteName(testWorkspaceID, endpointName) if isRedirect { - routeName = routeName + "-http-redirect" + routeName = redirectRouteName(endpointName) } httpRouteNamespacedName := namespacedName(routeName, namespace) - Eventually(func() bool { - err := k8sClient.Get(ctx, httpRouteNamespacedName, &createdHTTPRoute) - return err == nil - }, timeout, interval).Should(BeTrue(), "HTTPRoute should exist in cluster") + if err := k8sClient.Get(ctx, httpRouteNamespacedName, &createdHTTPRoute); err != nil { + Expect(k8sErrors.IsNotFound(err)).Should(BeTrue(), "unexpected error fetching HTTPRoute %s", routeName) + return + } deleteObject(&createdHTTPRoute) } diff --git a/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml b/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml index e4b576520..1d106f480 100644 --- a/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml +++ b/deploy/bundle/manifests/controller.devfile.io_devworkspaceoperatorconfigs.yaml @@ -62,12 +62,13 @@ spec: GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes should attach to when using the 'gateway-api' routing class. This field is required when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + by the cluster administrator before workspaces can use Gateway API routing. properties: name: description: Name is the name of the Gateway resource maxLength: 253 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string namespace: description: |- @@ -76,6 +77,7 @@ spec: as the DevWorkspace. maxLength: 63 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string required: - name diff --git a/deploy/deployment/kubernetes/combined.yaml b/deploy/deployment/kubernetes/combined.yaml index 56eb76e18..9f8661c75 100644 --- a/deploy/deployment/kubernetes/combined.yaml +++ b/deploy/deployment/kubernetes/combined.yaml @@ -63,12 +63,13 @@ spec: GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes should attach to when using the 'gateway-api' routing class. This field is required when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + by the cluster administrator before workspaces can use Gateway API routing. properties: name: description: Name is the name of the Gateway resource maxLength: 253 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string namespace: description: |- @@ -77,6 +78,7 @@ spec: as the DevWorkspace. maxLength: 63 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string required: - name diff --git a/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml b/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml index 81913ccdd..415d3c03f 100644 --- a/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml +++ b/deploy/deployment/kubernetes/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml @@ -63,12 +63,13 @@ spec: GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes should attach to when using the 'gateway-api' routing class. This field is required when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + by the cluster administrator before workspaces can use Gateway API routing. properties: name: description: Name is the name of the Gateway resource maxLength: 253 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string namespace: description: |- @@ -77,6 +78,7 @@ spec: as the DevWorkspace. maxLength: 63 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string required: - name diff --git a/deploy/deployment/openshift/combined.yaml b/deploy/deployment/openshift/combined.yaml index e2dfac5ed..c8c5396bd 100644 --- a/deploy/deployment/openshift/combined.yaml +++ b/deploy/deployment/openshift/combined.yaml @@ -63,12 +63,13 @@ spec: GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes should attach to when using the 'gateway-api' routing class. This field is required when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + by the cluster administrator before workspaces can use Gateway API routing. properties: name: description: Name is the name of the Gateway resource maxLength: 253 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string namespace: description: |- @@ -77,6 +78,7 @@ spec: as the DevWorkspace. maxLength: 63 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string required: - name diff --git a/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml b/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml index 81913ccdd..415d3c03f 100644 --- a/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml +++ b/deploy/deployment/openshift/objects/devworkspaceoperatorconfigs.controller.devfile.io.CustomResourceDefinition.yaml @@ -63,12 +63,13 @@ spec: GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes should attach to when using the 'gateway-api' routing class. This field is required when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + by the cluster administrator before workspaces can use Gateway API routing. properties: name: description: Name is the name of the Gateway resource maxLength: 253 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string namespace: description: |- @@ -77,6 +78,7 @@ spec: as the DevWorkspace. maxLength: 63 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string required: - name diff --git a/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml b/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml index a243a7287..a6bb840fd 100644 --- a/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml +++ b/deploy/templates/crd/bases/controller.devfile.io_devworkspaceoperatorconfigs.yaml @@ -61,12 +61,13 @@ spec: GatewayRef defines a reference to a Gateway API Gateway resource that HTTPRoutes should attach to when using the 'gateway-api' routing class. This field is required when routingClass is set to 'gateway-api'. The referenced Gateway must be provisioned - by the cluster administrator or Che Operator before workspaces can use Gateway API routing. + by the cluster administrator before workspaces can use Gateway API routing. properties: name: description: Name is the name of the Gateway resource maxLength: 253 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string namespace: description: |- @@ -75,6 +76,7 @@ spec: as the DevWorkspace. maxLength: 63 minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string required: - name diff --git a/main.go b/main.go index 0ed16ef1b..3d23e1e99 100644 --- a/main.go +++ b/main.go @@ -82,7 +82,7 @@ func init() { utilruntime.Must(controllerv1alpha1.AddToScheme(scheme)) utilruntime.Must(dwv1.AddToScheme(scheme)) utilruntime.Must(dwv2.AddToScheme(scheme)) - utilruntime.Must(gwapiv1.AddToScheme(scheme)) + utilruntime.Must(gwapiv1.Install(scheme)) if infrastructure.IsOpenShift() { utilruntime.Must(routev1.Install(scheme)) diff --git a/pkg/config/sync.go b/pkg/config/sync.go index 2cb12b275..34b6c84bd 100644 --- a/pkg/config/sync.go +++ b/pkg/config/sync.go @@ -669,6 +669,12 @@ func GetCurrentConfigString(currConfig *controller.OperatorConfiguration) string if routing.DefaultRoutingClass != defaultConfig.Routing.DefaultRoutingClass { config = append(config, fmt.Sprintf("routing.defaultRoutingClass=%s", routing.DefaultRoutingClass)) } + if routing.GatewayRef != nil { + config = append(config, fmt.Sprintf("routing.gatewayRef.name=%s", routing.GatewayRef.Name)) + if routing.GatewayRef.Namespace != nil { + config = append(config, fmt.Sprintf("routing.gatewayRef.namespace=%s", *routing.GatewayRef.Namespace)) + } + } } webhook := currConfig.Webhook if webhook != nil { diff --git a/pkg/provision/sync/diffopts.go b/pkg/provision/sync/diffopts.go index cb0e5aa51..5d3b92134 100644 --- a/pkg/provision/sync/diffopts.go +++ b/pkg/provision/sync/diffopts.go @@ -103,7 +103,7 @@ var httpRouteDiffOpts = cmp.Options{ cmpopts.IgnoreFields(gwapiv1.HTTPRoute{}, "TypeMeta", "ObjectMeta", "Status"), cmpopts.IgnoreFields(gwapiv1.BackendRef{}, "Weight"), cmpopts.IgnoreFields(gwapiv1.BackendObjectReference{}, "Group", "Kind", "Namespace"), - cmpopts.IgnoreFields(gwapiv1.ParentReference{}, "Group", "Kind", "Namespace"), + cmpopts.IgnoreFields(gwapiv1.ParentReference{}, "Group", "Kind"), } func getNameFromEnvFrom(source corev1.EnvFromSource) string { From d42d70caef5877524bb7213080045750adb3a2db Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Wed, 28 Oct 2026 10:33:31 -0400 Subject: [PATCH 6/8] fix: skip HTTPRoute sync when Gateway API is not installed The DevWorkspaceRouting reconciler synced HTTPRoutes unconditionally, so on clusters without the Gateway API CRDs (e.g. default OpenShift) listing HTTPRoutes failed with a no-match error. That error blocked every workspace - including cluster-tls/web-terminal routings that never use Gateway API - on the "Preparing HTTPRoutes" step until it timed out. Gate the HTTPRoute sync on infrastructure.IsGatewayAPIInstalled(), mirroring the Owns(&gwapiv1.HTTPRoute{}) watch registration in SetupWithManager. When the CRD is absent no HTTPRoutes can exist or be desired, so the sync is safely skipped. This is not reproducible in envtest because the suite always registers the HTTPRoute CRD; it is covered by the OpenShift e2e suite. Assisted-by: Claude Code Co-Authored-By: Claude Opus 4.8 Signed-off-by: Badre Tejado-Imam --- .../devworkspacerouting_controller.go | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index ed52cc173..ead4837b5 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -295,20 +295,25 @@ func (r *DevWorkspaceRoutingReconciler) Reconcile(ctx context.Context, req ctrl. clusterRoutingObj.Ingresses = clusterIngresses } - // Sync HTTPRoutes (always, so stale HTTPRoutes get cleaned up even when 0 are desired) - httpRoutesInSync, clusterHTTPRoutes, err := r.syncHTTPRoutes(instance, httpRoutes) - if err != nil { - failError := &sync.UnrecoverableSyncError{} - if errors.As(err, &failError) { - return reconcile.Result{}, r.markRoutingFailed(ctx, instance, err.Error()) + // Sync HTTPRoutes (always, so stale HTTPRoutes get cleaned up even when 0 are desired), + // but only when the Gateway API is installed on the cluster. Without the HTTPRoute CRD, + // listing HTTPRoutes fails, and since no HTTPRoutes can exist there is nothing to sync. + // This gate mirrors the Owns(&gwapiv1.HTTPRoute{}) watch registration in SetupWithManager. + if infrastructure.IsGatewayAPIInstalled() { + httpRoutesInSync, clusterHTTPRoutes, err := r.syncHTTPRoutes(instance, httpRoutes) + if err != nil { + failError := &sync.UnrecoverableSyncError{} + if errors.As(err, &failError) { + return reconcile.Result{}, r.markRoutingFailed(ctx, instance, err.Error()) + } + reqLogger.Error(err, "Error syncing HTTPRoutes") + return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") + } else if !httpRoutesInSync { + reqLogger.Info("HTTPRoutes not in sync") + return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") } - reqLogger.Error(err, "Error syncing HTTPRoutes") - return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") - } else if !httpRoutesInSync { - reqLogger.Info("HTTPRoutes not in sync") - return reconcile.Result{Requeue: true}, r.reconcileStatus(ctx, instance, nil, nil, false, "Preparing HTTPRoutes") + clusterRoutingObj.HTTPRoutes = clusterHTTPRoutes } - clusterRoutingObj.HTTPRoutes = clusterHTTPRoutes exposedEndpoints, endpointsAreReady, err := solver.GetExposedEndpoints(instance.Spec.Endpoints, clusterRoutingObj) if err != nil { From 26ff739530f46f791b94664422ba02774d1a4181 Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Mon, 30 Nov 2026 15:43:16 -0500 Subject: [PATCH 7/8] chore: adapt Gateway API routing to rebased main Rebased the Gateway API routing work onto the latest upstream/main and resolved the conflicts the rebase surfaced: - RoutingSolver now threads context.Context and GetDiscoverableServices ForEndpoints takes (ctx, endpoints, meta, client); update GatewayAPISolver to match the new interface and give it a client via NewGatewayAPISolver. - Use NewClusterSolver/ctx-aware reconcileStatus and markRoutingFailed call sites in the DevWorkspaceRouting controller. - Regenerate CRDs, CSV and deepcopy for the Gateway API config fields. Assisted-by: Claude Opus 4.8 Co-Authored-By: Claude Opus 4.8 Signed-off-by: Badre Tejado-Imam --- .../devworkspacerouting_controller.go | 1 + .../solvers/gateway_api_solver.go | 21 ++++++++++++++++--- .../devworkspacerouting/solvers/solver.go | 2 +- .../components/csv/clusterserviceversion.yaml | 1 - 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go index ead4837b5..85c8b22da 100644 --- a/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go +++ b/controllers/controller/devworkspacerouting/devworkspacerouting_controller.go @@ -336,6 +336,7 @@ func workspaceName(routing *controllerv1alpha1.DevWorkspaceRouting) string { return "" } return owner.Name +} // setFinalizer ensures a finalizer is set on a devWorkspaceRouting instance; no-op if finalizer is already present. func (r *DevWorkspaceRoutingReconciler) setFinalizer(reqLogger logr.Logger, solver solvers.RoutingSolver, m *controllerv1alpha1.DevWorkspaceRouting) error { diff --git a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go index 0088191f5..408aebea8 100644 --- a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go +++ b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver.go @@ -15,9 +15,11 @@ package solvers import ( + "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" @@ -31,10 +33,19 @@ const httpRouteRequestTimeout = gwapiv1.Duration("10h") // GatewayAPISolver exposes endpoints using Kubernetes Gateway API HTTPRoutes // HTTPRoutes are attached to a Gateway specified in the operator configuration -type GatewayAPISolver struct{} +type GatewayAPISolver struct { + client client.Client +} var _ RoutingSolver = (*GatewayAPISolver)(nil) +// NewGatewayAPISolver creates a new GatewayAPISolver with the provided dependencies +func NewGatewayAPISolver(client client.Client) *GatewayAPISolver { + return &GatewayAPISolver{ + client: client, + } +} + func (s *GatewayAPISolver) FinalizerRequired(*controllerv1alpha1.DevWorkspaceRouting) bool { return false } @@ -43,7 +54,7 @@ func (s *GatewayAPISolver) Finalize(*controllerv1alpha1.DevWorkspaceRouting) err return nil } -func (s *GatewayAPISolver) GetSpecObjects(routing *controllerv1alpha1.DevWorkspaceRouting, workspaceMeta DevWorkspaceMetadata) (RoutingObjects, error) { +func (s *GatewayAPISolver) GetSpecObjects(ctx context.Context, routing *controllerv1alpha1.DevWorkspaceRouting, workspaceMeta DevWorkspaceMetadata) (RoutingObjects, error) { routingObjects := RoutingObjects{} // Validate Gateway reference is configured @@ -62,7 +73,11 @@ func (s *GatewayAPISolver) GetSpecObjects(routing *controllerv1alpha1.DevWorkspa // Create Services (same as basic solver - HTTPRoutes route to Services) services := getServicesForEndpoints(spec.Endpoints, workspaceMeta) - services = append(services, GetDiscoverableServicesForEndpoints(spec.Endpoints, workspaceMeta)...) + discoverableServices, err := GetDiscoverableServicesForEndpoints(ctx, spec.Endpoints, workspaceMeta, s.client) + if err != nil { + return RoutingObjects{}, err + } + services = append(services, discoverableServices...) routingObjects.Services = services // Create HTTPRoutes for Gateway API diff --git a/controllers/controller/devworkspacerouting/solvers/solver.go b/controllers/controller/devworkspacerouting/solvers/solver.go index d468fcf2f..0e6f3660a 100644 --- a/controllers/controller/devworkspacerouting/solvers/solver.go +++ b/controllers/controller/devworkspacerouting/solvers/solver.go @@ -121,7 +121,7 @@ func (_ *SolverGetter) GetSolver(client client.Client, routingClass controllerv1 if !infrastructure.IsGatewayAPIInstalled() { return nil, fmt.Errorf("routing class %s requires Gateway API CRDs to be installed on the cluster", routingClass) } - return &GatewayAPISolver{}, nil + return NewGatewayAPISolver(client), nil default: return nil, RoutingNotSupported } diff --git a/deploy/templates/components/csv/clusterserviceversion.yaml b/deploy/templates/components/csv/clusterserviceversion.yaml index 9491e5d78..bff7278cb 100644 --- a/deploy/templates/components/csv/clusterserviceversion.yaml +++ b/deploy/templates/components/csv/clusterserviceversion.yaml @@ -1,4 +1,3 @@ ---- apiVersion: operators.coreos.com/v1alpha1 kind: ClusterServiceVersion metadata: From 05ef242cd9ea070aa6b2859a036e0873745831c3 Mon Sep 17 00:00:00 2001 From: Badre Tejado-Imam Date: Tue, 1 Dec 2026 10:58:24 -0500 Subject: [PATCH 8/8] test: add unit tests for Gateway API routing Cover the previously-untested gateway-api code flagged by codecov/patch: - gateway_api_solver_test.go: GatewayAPISolver spec-object generation (HTTP->HTTPS 301 redirect route on port 80, HTTPS backend route on port 443 with the 10h request timeout and workspace Service backend), RoutingInvalid validation when gatewayRef/clusterHostSuffix are missing, gateway-namespace override, exposed-endpoint resolution (ready and not-ready), and the IsGatewayAPIInstalled gate in SolverGetter. - sync_httproutes_test.go: syncHTTPRoutes create + stale-route deletion + convergence, cluster HTTPRoute listing by workspace label, and the getHTTPRoutesToDelete / listContainsHTTPRouteByName helpers. gateway_api_solver.go and sync_httproutes.go go from 0% to ~90%+ coverage. Assisted-by: Claude Opus 4.8 Co-Authored-By: Claude Opus 4.8 Signed-off-by: Badre Tejado-Imam --- .../solvers/gateway_api_solver_test.go | 303 ++++++++++++++++++ .../sync_httproutes_test.go | 154 +++++++++ 2 files changed, 457 insertions(+) create mode 100644 controllers/controller/devworkspacerouting/solvers/gateway_api_solver_test.go create mode 100644 controllers/controller/devworkspacerouting/sync_httproutes_test.go diff --git a/controllers/controller/devworkspacerouting/solvers/gateway_api_solver_test.go b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver_test.go new file mode 100644 index 000000000..ca80f1962 --- /dev/null +++ b/controllers/controller/devworkspacerouting/solvers/gateway_api_solver_test.go @@ -0,0 +1,303 @@ +// Copyright (c) 2019-2026 Red Hat, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Generated by Claude Opus 4.8 + +package solvers + +import ( + "context" + "errors" + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" + "github.com/devfile/devworkspace-operator/pkg/common" + "github.com/devfile/devworkspace-operator/pkg/config" + "github.com/devfile/devworkspace-operator/pkg/constants" + "github.com/devfile/devworkspace-operator/pkg/infrastructure" +) + +const ( + testGatewayName = "che-gateway" + testHostSuffix = "example.test" +) + +// Generated by Claude Opus 4.8 +func newGatewayAPISolverTest(t *testing.T, gatewayRef *controllerv1alpha1.GatewayReference, hostSuffix string) (*GatewayAPISolver, *controllerv1alpha1.DevWorkspaceRouting, DevWorkspaceMetadata) { + t.Helper() + previousConfig := config.GetGlobalConfig() + config.SetGlobalConfigForTesting(&controllerv1alpha1.OperatorConfiguration{ + Routing: &controllerv1alpha1.RoutingConfig{ + ClusterHostSuffix: hostSuffix, + GatewayRef: gatewayRef, + }, + }) + t.Cleanup(func() { config.SetGlobalConfigForTesting(previousConfig) }) + infrastructure.InitializeForTesting(infrastructure.Kubernetes) + + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + cl := fake.NewClientBuilder().WithScheme(scheme).Build() + + solver := NewGatewayAPISolver(cl) + meta := DevWorkspaceMetadata{ + DevWorkspaceId: "workspace-id", + DevWorkspaceName: "workspace", + Namespace: "workspace-namespace", + PodSelector: map[string]string{"workspace": "workspace-id", "component": "devworkspace"}, + } + return solver, routingInNamespace(meta.Namespace), meta +} + +// Generated by Claude Opus 4.8 +func routingInNamespace(namespace string) *controllerv1alpha1.DevWorkspaceRouting { + routing := routingForEndpoints(map[string]controllerv1alpha1.EndpointList{ + "main": { + testEndpoint("web", 8080, controllerv1alpha1.PublicEndpointExposure, false, "http"), + testEndpoint("db", 5432, controllerv1alpha1.InternalEndpointExposure, false, "tcp"), + testEndpoint("hidden", 9000, controllerv1alpha1.NoneEndpointExposure, false, "http"), + }, + }) + routing.Namespace = namespace + return routing +} + +// Generated by Claude Opus 4.8 +func TestGatewayAPISolverGetSpecObjects(t *testing.T) { + solver, routing, meta := newGatewayAPISolverTest(t, &controllerv1alpha1.GatewayReference{Name: testGatewayName}, testHostSuffix) + + objects, err := solver.GetSpecObjects(context.Background(), routing, meta) + if err != nil { + t.Fatal(err) + } + + // One aggregate Service, and two HTTPRoutes (backend + redirect) for the single public endpoint. + if len(objects.Services) != 1 { + t.Fatalf("expected 1 aggregate Service, got %d", len(objects.Services)) + } + if len(objects.HTTPRoutes) != 2 { + t.Fatalf("expected 2 HTTPRoutes (backend + redirect), got %d", len(objects.HTTPRoutes)) + } + + epName := common.EndpointName("web") + backendName := common.RouteName(meta.DevWorkspaceId, epName) + redirectName := backendName + "-http-redirect" + wantHostname := common.EndpointHostname(testHostSuffix, meta.DevWorkspaceId, epName, 8080) + + routes := map[string]gwapiv1.HTTPRoute{} + for _, r := range objects.HTTPRoutes { + routes[r.Name] = r + } + + backend, ok := routes[backendName] + if !ok { + t.Fatalf("backend HTTPRoute %q not found; got %v", backendName, keysOf(routes)) + } + assertCommonRouteMeta(t, backend, meta.Namespace, "web") + assertParentRef(t, backend, testGatewayName, meta.Namespace, 443) + if len(backend.Spec.Hostnames) != 1 || string(backend.Spec.Hostnames[0]) != wantHostname { + t.Errorf("backend hostnames = %v, want [%s]", backend.Spec.Hostnames, wantHostname) + } + if len(backend.Spec.Rules) != 1 || len(backend.Spec.Rules[0].BackendRefs) != 1 { + t.Fatalf("backend route rules/backendRefs malformed: %#v", backend.Spec.Rules) + } + ref := backend.Spec.Rules[0].BackendRefs[0] + if string(ref.Name) != common.ServiceName(meta.DevWorkspaceId) { + t.Errorf("backendRef name = %q, want %q", ref.Name, common.ServiceName(meta.DevWorkspaceId)) + } + if ref.Port == nil || *ref.Port != gwapiv1.PortNumber(8080) { + t.Errorf("backendRef port = %v, want 8080", ref.Port) + } + if backend.Spec.Rules[0].Timeouts == nil || backend.Spec.Rules[0].Timeouts.Request == nil || + *backend.Spec.Rules[0].Timeouts.Request != httpRouteRequestTimeout { + t.Errorf("backend request timeout = %v, want %s", backend.Spec.Rules[0].Timeouts, httpRouteRequestTimeout) + } + + redirect, ok := routes[redirectName] + if !ok { + t.Fatalf("redirect HTTPRoute %q not found; got %v", redirectName, keysOf(routes)) + } + assertCommonRouteMeta(t, redirect, meta.Namespace, "web") + assertParentRef(t, redirect, testGatewayName, meta.Namespace, 80) + if len(redirect.Spec.Rules) != 1 || len(redirect.Spec.Rules[0].Filters) != 1 { + t.Fatalf("redirect route rules/filters malformed: %#v", redirect.Spec.Rules) + } + filter := redirect.Spec.Rules[0].Filters[0] + if filter.Type != gwapiv1.HTTPRouteFilterRequestRedirect || filter.RequestRedirect == nil { + t.Fatalf("redirect filter = %#v, want RequestRedirect", filter) + } + if filter.RequestRedirect.Scheme == nil || *filter.RequestRedirect.Scheme != "https" { + t.Errorf("redirect scheme = %v, want https", filter.RequestRedirect.Scheme) + } + if filter.RequestRedirect.StatusCode == nil || *filter.RequestRedirect.StatusCode != 301 { + t.Errorf("redirect status code = %v, want 301", filter.RequestRedirect.StatusCode) + } + + // Exposed endpoints should be ready with an https URL for the backend hostname. + exposed, ready, err := solver.GetExposedEndpoints(routing.Spec.Endpoints, objects) + if err != nil || !ready { + t.Fatalf("GetExposedEndpoints() = (%v, %t, %v), want ready without error", exposed, ready, err) + } + if len(exposed["main"]) != 1 || exposed["main"][0].Name != "web" || exposed["main"][0].Url != "https://"+wantHostname { + t.Fatalf("exposed endpoints = %#v, want single https URL for web", exposed) + } +} + +// Generated by Claude Opus 4.8 +func TestGatewayAPISolverGatewayNamespaceOverride(t *testing.T) { + gatewayNamespace := "openshift-gateway" + solver, routing, meta := newGatewayAPISolverTest(t, + &controllerv1alpha1.GatewayReference{Name: testGatewayName, Namespace: &gatewayNamespace}, testHostSuffix) + + objects, err := solver.GetSpecObjects(context.Background(), routing, meta) + if err != nil { + t.Fatal(err) + } + for _, r := range objects.HTTPRoutes { + assertParentRefNamespace(t, r, gatewayNamespace) + } +} + +// Generated by Claude Opus 4.8 +func TestGatewayAPISolverGetSpecObjectsInvalid(t *testing.T) { + tests := []struct { + name string + gatewayRef *controllerv1alpha1.GatewayReference + hostSuffix string + }{ + {name: "missing gatewayRef", gatewayRef: nil, hostSuffix: testHostSuffix}, + {name: "missing clusterHostSuffix", gatewayRef: &controllerv1alpha1.GatewayReference{Name: testGatewayName}, hostSuffix: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + solver, routing, meta := newGatewayAPISolverTest(t, tt.gatewayRef, tt.hostSuffix) + _, err := solver.GetSpecObjects(context.Background(), routing, meta) + var invalid *RoutingInvalid + if !errors.As(err, &invalid) { + t.Fatalf("GetSpecObjects() error = %v, want *RoutingInvalid", err) + } + }) + } +} + +// Generated by Claude Opus 4.8 +func TestGatewayAPISolverGetExposedEndpointsNotReady(t *testing.T) { + solver, routing, _ := newGatewayAPISolverTest(t, &controllerv1alpha1.GatewayReference{Name: testGatewayName}, testHostSuffix) + + // No HTTPRoutes present on the cluster object => the public endpoint cannot resolve a URL. + exposed, ready, err := solver.GetExposedEndpoints(routing.Spec.Endpoints, RoutingObjects{}) + if err != nil { + t.Fatal(err) + } + if ready { + t.Fatalf("expected not-ready when no HTTPRoutes exist, got ready=true (%#v)", exposed) + } + if len(exposed["main"]) != 1 || exposed["main"][0].Url != "" { + t.Fatalf("expected the public endpoint with an empty URL, got %#v", exposed) + } +} + +// Generated by Claude Opus 4.8 +func TestGatewayAPISolverFinalizer(t *testing.T) { + solver := NewGatewayAPISolver(nil) + if solver.FinalizerRequired(nil) { + t.Error("FinalizerRequired() = true, want false") + } + if err := solver.Finalize(nil); err != nil { + t.Errorf("Finalize() = %v, want nil", err) + } +} + +// Generated by Claude Opus 4.8 +func TestGetSolverGatewayAPIGate(t *testing.T) { + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + cl := fake.NewClientBuilder().WithScheme(scheme).Build() + infrastructure.InitializeForTesting(infrastructure.Kubernetes) + + previous := infrastructure.IsGatewayAPIInstalled() + t.Cleanup(func() { infrastructure.SetGatewayAPIInstalledForTesting(previous) }) + + infrastructure.SetGatewayAPIInstalledForTesting(true) + solver, err := (&SolverGetter{}).GetSolver(cl, controllerv1alpha1.DevWorkspaceRoutingGatewayAPI) + if err != nil { + t.Fatalf("GetSolver(gateway-api) with API installed returned error: %v", err) + } + if _, ok := solver.(*GatewayAPISolver); !ok { + t.Fatalf("GetSolver returned %T, want *GatewayAPISolver", solver) + } + + infrastructure.SetGatewayAPIInstalledForTesting(false) + if _, err := (&SolverGetter{}).GetSolver(cl, controllerv1alpha1.DevWorkspaceRoutingGatewayAPI); err == nil { + t.Fatal("GetSolver(gateway-api) with API not installed returned no error") + } +} + +// Generated by Claude Opus 4.8 +func assertCommonRouteMeta(t *testing.T, route gwapiv1.HTTPRoute, namespace, endpointName string) { + t.Helper() + if route.Namespace != namespace { + t.Errorf("route %q namespace = %q, want %q", route.Name, route.Namespace, namespace) + } + if route.Labels[constants.DevWorkspaceIDLabel] != "workspace-id" { + t.Errorf("route %q missing workspace id label: %v", route.Name, route.Labels) + } + if route.Annotations[constants.DevWorkspaceEndpointNameAnnotation] != endpointName { + t.Errorf("route %q endpoint-name annotation = %q, want %q", route.Name, route.Annotations[constants.DevWorkspaceEndpointNameAnnotation], endpointName) + } +} + +// Generated by Claude Opus 4.8 +func assertParentRef(t *testing.T, route gwapiv1.HTTPRoute, gatewayName, namespace string, port gwapiv1.PortNumber) { + t.Helper() + if len(route.Spec.ParentRefs) != 1 { + t.Fatalf("route %q parentRefs = %#v, want exactly one", route.Name, route.Spec.ParentRefs) + } + ref := route.Spec.ParentRefs[0] + if string(ref.Name) != gatewayName { + t.Errorf("route %q parentRef name = %q, want %q", route.Name, ref.Name, gatewayName) + } + if ref.Port == nil || *ref.Port != port { + t.Errorf("route %q parentRef port = %v, want %d", route.Name, ref.Port, port) + } + if ref.Namespace == nil || string(*ref.Namespace) != namespace { + t.Errorf("route %q parentRef namespace = %v, want %q", route.Name, ref.Namespace, namespace) + } +} + +// Generated by Claude Opus 4.8 +func assertParentRefNamespace(t *testing.T, route gwapiv1.HTTPRoute, namespace string) { + t.Helper() + if len(route.Spec.ParentRefs) != 1 || route.Spec.ParentRefs[0].Namespace == nil || + string(*route.Spec.ParentRefs[0].Namespace) != namespace { + t.Errorf("route %q parentRef namespace = %#v, want %q", route.Name, route.Spec.ParentRefs, namespace) + } +} + +// Generated by Claude Opus 4.8 +func keysOf(m map[string]gwapiv1.HTTPRoute) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return keys +} diff --git a/controllers/controller/devworkspacerouting/sync_httproutes_test.go b/controllers/controller/devworkspacerouting/sync_httproutes_test.go new file mode 100644 index 000000000..3635402b7 --- /dev/null +++ b/controllers/controller/devworkspacerouting/sync_httproutes_test.go @@ -0,0 +1,154 @@ +// Copyright (c) 2019-2026 Red Hat, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Generated by Claude Opus 4.8 + +package devworkspacerouting + +import ( + "context" + "testing" + + "github.com/go-logr/logr" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1" + "github.com/devfile/devworkspace-operator/pkg/constants" +) + +// Generated by Claude Opus 4.8 +func testHTTPRoute(name, namespace, workspaceID string) gwapiv1.HTTPRoute { + return gwapiv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + Labels: map[string]string{constants.DevWorkspaceIDLabel: workspaceID}, + }, + } +} + +// Generated by Claude Opus 4.8 +func httpRouteTestScheme(t *testing.T) *runtime.Scheme { + t.Helper() + scheme := runtime.NewScheme() + if err := gwapiv1.Install(scheme); err != nil { + t.Fatal(err) + } + if err := controllerv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + return scheme +} + +// Generated by Claude Opus 4.8 +func TestListContainsHTTPRouteByName(t *testing.T) { + list := []gwapiv1.HTTPRoute{testHTTPRoute("a", "ns", "ws"), testHTTPRoute("b", "ns", "ws")} + if found, idx := listContainsHTTPRouteByName(testHTTPRoute("b", "ns", "ws"), list); !found || idx != 1 { + t.Errorf("listContainsHTTPRouteByName(b) = (%t, %d), want (true, 1)", found, idx) + } + if found, idx := listContainsHTTPRouteByName(testHTTPRoute("missing", "ns", "ws"), list); found || idx != -1 { + t.Errorf("listContainsHTTPRouteByName(missing) = (%t, %d), want (false, -1)", found, idx) + } +} + +// Generated by Claude Opus 4.8 +func TestGetHTTPRoutesToDelete(t *testing.T) { + cluster := []gwapiv1.HTTPRoute{ + testHTTPRoute("keep", "ns", "ws"), + testHTTPRoute("stale-1", "ns", "ws"), + testHTTPRoute("stale-2", "ns", "ws"), + } + spec := []gwapiv1.HTTPRoute{testHTTPRoute("keep", "ns", "ws")} + + toDelete := getHTTPRoutesToDelete(cluster, spec) + if len(toDelete) != 2 { + t.Fatalf("expected 2 routes to delete, got %d: %v", len(toDelete), toDelete) + } + names := map[string]bool{toDelete[0].Name: true, toDelete[1].Name: true} + if !names["stale-1"] || !names["stale-2"] { + t.Errorf("toDelete = %v, want stale-1 and stale-2", names) + } + + // Nothing to delete when cluster matches spec exactly. + if got := getHTTPRoutesToDelete(spec, spec); len(got) != 0 { + t.Errorf("getHTTPRoutesToDelete(spec, spec) = %v, want empty", got) + } +} + +// Generated by Claude Opus 4.8 +func TestGetClusterHTTPRoutes(t *testing.T) { + scheme := httpRouteTestScheme(t) + mine := testHTTPRoute("mine", "ns", "wsid") + otherWorkspace := testHTTPRoute("other-ws", "ns", "other-wsid") + otherNamespace := testHTTPRoute("other-ns", "other", "wsid") + cl := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&mine, &otherWorkspace, &otherNamespace).Build() + r := DevWorkspaceRoutingReconciler{Client: cl, Scheme: scheme, Log: logr.Discard()} + + routing := &controllerv1alpha1.DevWorkspaceRouting{ + ObjectMeta: metav1.ObjectMeta{Name: "routing", Namespace: "ns"}, + Spec: controllerv1alpha1.DevWorkspaceRoutingSpec{DevWorkspaceId: "wsid"}, + } + got, err := r.getClusterHTTPRoutes(routing) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Name != "mine" { + t.Fatalf("getClusterHTTPRoutes() = %v, want only the matching-workspace, matching-namespace route", got) + } +} + +// Generated by Claude Opus 4.8 +func TestSyncHTTPRoutes(t *testing.T) { + scheme := httpRouteTestScheme(t) + stale := testHTTPRoute("stale-route", "ns", "wsid") + cl := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&stale).Build() + r := DevWorkspaceRoutingReconciler{Client: cl, Scheme: scheme, Log: logr.Discard()} + + routing := &controllerv1alpha1.DevWorkspaceRouting{ + ObjectMeta: metav1.ObjectMeta{Name: "routing", Namespace: "ns"}, + Spec: controllerv1alpha1.DevWorkspaceRoutingSpec{DevWorkspaceId: "wsid"}, + } + spec := []gwapiv1.HTTPRoute{testHTTPRoute("new-route", "ns", "wsid")} + + // First pass: stale route deleted, new route created => not yet in sync. + inSync, _, err := r.syncHTTPRoutes(routing, spec) + if err != nil { + t.Fatal(err) + } + if inSync { + t.Fatal("first syncHTTPRoutes() reported in-sync, want not-in-sync after create/delete") + } + if err := cl.Get(context.TODO(), client.ObjectKey{Namespace: "ns", Name: "stale-route"}, &gwapiv1.HTTPRoute{}); !apierrors.IsNotFound(err) { + t.Fatalf("stale route still present: %v", err) + } + if err := cl.Get(context.TODO(), client.ObjectKey{Namespace: "ns", Name: "new-route"}, &gwapiv1.HTTPRoute{}); err != nil { + t.Fatalf("new route not created: %v", err) + } + + // Second pass: desired route now exists and matches => in sync. + inSync, clusterRoutes, err := r.syncHTTPRoutes(routing, spec) + if err != nil { + t.Fatal(err) + } + if !inSync { + t.Fatal("second syncHTTPRoutes() reported not-in-sync, want in-sync") + } + if len(clusterRoutes) != 1 || clusterRoutes[0].Name != "new-route" { + t.Fatalf("clusterRoutes = %v, want [new-route]", clusterRoutes) + } +}