// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of Cilium package model import ( "sort" "strconv" "strings" "time" "k8s.io/apimachinery/pkg/types" "github.com/cilium/cilium/pkg/slices" ) // Model holds an abstracted data model representing the translation // of various types of Kubernetes config to Cilium config. type Model struct { HTTP []HTTPListener `json:"http,omitempty"` TLSPassthrough []TLSPassthroughListener `json:"tls_passthrough,omitempty"` L4 []L4Listener `json:"l4,omitempty"` HTTPOptions *HTTPOptions `json:"http_options,omitempty"` Telemetry *Telemetry `json:"telemetry,omitempty"` } type HTTPOptions struct { GRPCWebTranslation *GRPCWebTranslationConfig `json:"grpc_web_translation,omitempty"` } type GRPCWebTranslationConfig struct { Enabled bool `json:"enabled"` L4 []L4Listener `json:"l4,omitempty"` } func (m *Model) GetListeners() []Listener { var listeners []Listener for i := range m.HTTP { listeners = append(listeners, &m.HTTP[i]) } for i := range m.TLSPassthrough { listeners = append(listeners, &m.TLSPassthrough[i]) } for i := range m.L4 { listeners = append(listeners, &m.L4[i]) } return listeners } func (m *Model) GRPCWebTranslationEnabled() bool { return m == nil || m.HTTPOptions == nil || m.HTTPOptions.GRPCWebTranslation == nil || m.HTTPOptions.GRPCWebTranslation.Enabled } type Listener interface { GetSources() []FullyQualifiedResource GetPort() uint32 GetAnnotations() map[string]string GetLabels() map[string]string GetService() *Service GetProtocol() L4Protocol } // HTTPListener holds configuration for any listener that terminates and proxies HTTP // including HTTP and HTTPS. // Each holds the configuration info for one distinct HTTP listener, by // - Hostname // - TLS // - Address // - Port type HTTPListener struct { // Name of the HTTPListener Name string `json:"name,omitempty"` // Sources is a slice of fully qualified resources this HTTPListener is sourced // from. Sources []FullyQualifiedResource `json:"sources,omitempty"` // IPAddress that the listener should listen on. // The string must be parseable as an IP address. Address string `json:"address,omitempty"` // Port on which the service can be expected to be accessed by clients. Port uint32 `json:"port,omitempty"` // Hostname that the listener should match. // Wildcards are supported in prefix or suffix forms, or the special wildcard `*`. // An empty list means that the Listener should match all hostnames. Hostname string `json:"hostname,omitempty"` // TLS Certificate information. If omitted, then the listener is a cleartext HTTP listener. TLS []TLSSecret `json:"tls,omitempty"` // Routes associated with HTTP traffic to the service. // An empty list means that traffic will not be routed. Routes []HTTPRoute `json:"routes,omitempty"` // Service configuration Service *Service `json:"service,omitempty"` // Infrastructure configuration Infrastructure *Infrastructure `json:"infrastructure,omitempty"` // ForceHTTPtoHTTPSRedirect enforces that, for HTTPListeners that have a // TLS field set and create a HTTPS listener, an equivalent plaintext HTTP // listener will be created that redirects requests from HTTP to HTTPS. // // This plaintext listener will override any other plaintext HTTP config in // the final rendered Envoy Config. ForceHTTPtoHTTPSRedirect bool `json:"force_http_to_https_redirect,omitempty"` // ServerHeaderTransformation controls the HTTP "Server" header. // OVERWRITE (default): Overwrite any Server header with "envoy". // APPEND_IF_ABSENT: If no Server header is present, append Server "envoy". If a Server header is present, pass it through. // PASS_THROUGH: Pass through the value of the server header, and do not append a header if none is present. ServerHeaderTransformation ServerHeaderTransformation `json:"server_header_transformation,omitempty"` // Gamma is an indicator if this listener is a gamma listener Gamma bool `json:"gamma,omitempty"` } // Telemetry defines observability configuration. type Telemetry struct { // AccessLogs configures access logging. AccessLogs map[AccessLogsTarget][]AccessLogs `json:"access_logs,omitempty"` // NamespacedName identifies the Gateway associated with this telemetry configuration. NamespacedName types.NamespacedName `json:"namespaced_name"` } // AccessLogs defines access logging configuration. type AccessLogs struct { // Format specifies the access log format ("Text" or "JSON"). Format AccessLogsFormat `json:"format"` // Text specifies the log template used when format is "Text". Text string `json:"text,omitempty"` // JSON specifies the field mapping used when format is "JSON". JSON map[string]string `json:"json,omitempty"` } // AccessLogsFormat specifies the access log output format. type AccessLogsFormat string const ( AccessLogsFormatText AccessLogsFormat = "Text" AccessLogsFormatJSON AccessLogsFormat = "JSON" ) // AccessLogsTarget specifies where access logs are emitted. type AccessLogsTarget string const ( // AccessLogsTargetHTTP emits access logs from Envoy HTTP connection managers. AccessLogsTargetHTTP AccessLogsTarget = "HTTP" // AccessLogsTargetTCP emits access logs from Envoy TCP proxies, including TLS passthrough. AccessLogsTargetTCP AccessLogsTarget = "TCP" ) func (l HTTPListener) GetSources() []FullyQualifiedResource { return l.Sources } func (l HTTPListener) GetPort() uint32 { return l.Port } func (l HTTPListener) GetAnnotations() map[string]string { if l.Infrastructure != nil { return l.Infrastructure.Annotations } return nil } func (l HTTPListener) GetLabels() map[string]string { if l.Infrastructure != nil { return l.Infrastructure.Labels } return nil } func (l HTTPListener) GetService() *Service { return l.Service } func (l HTTPListener) GetProtocol() L4Protocol { return L4ProtocolTCP } // TLSPassthroughListener holds configuration for any listener that proxies TLS // based on the SNI value. // Each holds the configuration info for one distinct TLS listener, by // - Hostname // - Address // - Port type TLSPassthroughListener struct { // Name of the TLSListener Name string `json:"name,omitempty"` // Sources is a slice of fully qualified resources this TLSListener is sourced // from. Sources []FullyQualifiedResource `json:"sources,omitempty"` // IPAddress that the listener should listen on. // The string must be parseable as an IP address. Address string `json:"address,omitempty"` // Port on which the service can be expected to be accessed by clients. Port uint32 `json:"port,omitempty"` // Hostname that the listener should match. // Wildcards are supported in prefix or suffix forms, or the special wildcard `*`. // An empty list means that the Listener should match all hostnames. Hostname string `json:"hostname,omitempty"` // Routes associated with traffic to the service. // An empty list means that traffic will not be routed. Routes []TLSPassthroughRoute `json:"routes,omitempty"` // Service configuration Service *Service `json:"service,omitempty"` // Infrastructure configuration Infrastructure *Infrastructure `json:"infrastructure,omitempty"` } func (l TLSPassthroughListener) GetAnnotations() map[string]string { if l.Infrastructure != nil { return l.Infrastructure.Annotations } return nil } func (l TLSPassthroughListener) GetLabels() map[string]string { if l.Infrastructure != nil { return l.Infrastructure.Labels } return nil } func (l TLSPassthroughListener) GetSources() []FullyQualifiedResource { return l.Sources } func (l TLSPassthroughListener) GetPort() uint32 { return l.Port } func (l TLSPassthroughListener) GetService() *Service { return l.Service } func (l TLSPassthroughListener) GetProtocol() L4Protocol { return L4ProtocolTCP } type L4Protocol string const ( L4ProtocolTCP L4Protocol = "TCP" L4ProtocolUDP L4Protocol = "UDP" ) // L4Listener holds configuration for TCP or UDP listeners. type L4Listener struct { // Name of the listener Name string `json:"name,omitempty"` // Sources is a slice of fully qualified resources this listener is sourced from. Sources []FullyQualifiedResource `json:"sources,omitempty"` // IPAddress that the listener should listen on. Address string `json:"address,omitempty"` // Port on which the service can be expected to be accessed by clients. Port uint32 `json:"port,omitempty"` // Protocol of the listener (TCP or UDP). Protocol L4Protocol `json:"protocol,omitempty"` // Routes associated with traffic to the service. Routes []L4Route `json:"routes,omitempty"` // Service configuration Service *Service `json:"service,omitempty"` // Infrastructure configuration Infrastructure *Infrastructure `json:"infrastructure,omitempty"` } func (l L4Listener) GetAnnotations() map[string]string { if l.Infrastructure != nil { return l.Infrastructure.Annotations } return nil } func (l L4Listener) GetLabels() map[string]string { if l.Infrastructure != nil { return l.Infrastructure.Labels } return nil } func (l L4Listener) GetSources() []FullyQualifiedResource { return l.Sources } func (l L4Listener) GetPort() uint32 { return l.Port } func (l L4Listener) GetService() *Service { return l.Service } func (l L4Listener) GetProtocol() L4Protocol { return l.Protocol } // L4Route holds the details needed to route TCP/UDP traffic to backends. type L4Route struct { Name string `json:"name,omitempty"` // Backends handling the requests. Backends []Backend `json:"backends,omitempty"` } // Service holds the configuration for desired Service details // Note: This is a subset of the Service.Spec struct from k8s Service. Not all fields are supported. type Service struct { // Type is the type of service that is being used for Listener (e.g. Load Balancer or Node port) // Defaults to Load Balancer type Type string `json:"type,omitempty"` // InsecureNodePort is the back-end port of the service that is being used for HTTP Listener // Applicable only if Type is Node NodePort InsecureNodePort *uint32 `json:"insecure_node_port,omitempty"` // SecureNodePort is the back-end port of the service that is being used for HTTPS Listener // Applicable only if Type is Node NodePort SecureNodePort *uint32 `json:"secure_node_port,omitempty"` ExternalTrafficPolicy string `json:"external_traffic_policy,omitempty"` LoadBalancerClass *string `json:"load_balancer_class,omitempty"` LoadBalancerSourceRanges []string `json:"load_balancer_source_ranges,omitempty"` LoadBalancerSourceRangesPolicy string `json:"load_balancer_source_ranges_policy,omitempty"` IPFamilies []string `json:"ip_families,omitempty"` IPFamilyPolicy *string `json:"ip_family_policy,omitempty"` AllocateLoadBalancerNodePorts *bool `json:"allocate_load_balancer_node_ports,omitempty"` TrafficDistribution *string `json:"traffic_distribution,omitempty"` } // FullyQualifiedResource stores the full details of a Kubernetes resource, including // the Group, Version, and Kind. // Namespace must be set to the empty string for cluster-scoped resources. type FullyQualifiedResource struct { Name string `json:"name,omitempty"` Namespace string `json:"namespace,omitempty"` Group string `json:"group,omitempty"` Version string `json:"version,omitempty"` Kind string `json:"kind,omitempty"` UID string `json:"uid,omitempty"` } // HTTPRouteRule identifies the Gateway API HTTPRoute rule and match that // produced a model HTTPRoute. type HTTPRouteRule struct { Source FullyQualifiedResource RuleIndex int MatchIndex int } func (r HTTPRouteRule) key() string { return "httproute-rule:" + strings.Join([]string{ r.Source.Group, r.Source.Version, r.Source.Kind, r.Source.Namespace, r.Source.Name, r.Source.UID, strconv.Itoa(r.RuleIndex), strconv.Itoa(r.MatchIndex), }, "/") } // TLSSecret holds a reference to a secret containing a TLS keypair. type TLSSecret struct { Name string `json:"name,omitempty"` Namespace string `json:"namespace,omitempty"` } // DirectResponse holds configuration for a direct response. type DirectResponse struct { StatusCode int `json:"status_code,omitempty"` Body string `json:"body,omitempty"` } // Header is a key-value pair. type Header struct { Name string `json:"name,omitempty"` Value string `json:"value,omitempty"` } // HTTPHeaderFilter holds configuration for a request header filter. type HTTPHeaderFilter struct { // HeadersToAdd is a list of headers to add to the request. // Existing headers with the same name will be appended to. HeadersToAdd []Header `json:"headers_to_add,omitempty"` // HeadersToSet is a list of headers to set in the request. // Existing headers will be overwritten. HeadersToSet []Header `json:"headers_to_set,omitempty"` // HeadersToRemove is a list of headers to remove from the request. HeadersToRemove []string `json:"headers_to_remove,omitempty"` } // HTTPRequestRedirectFilter holds configuration for a request redirect. type HTTPRequestRedirectFilter struct { // 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 *string `json:"scheme,omitempty"` // Hostname is the hostname to be used in the value of the `Location` // header in the response. // When empty, the hostname of the request is used. Hostname *string `json:"hostname,omitempty"` // 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. Path *StringMatch `json:"path,omitempty"` // Port is the port to be used in the value of the `Location` // header in the response. // When empty, port (if specified) of the request is used. Port *int32 `json:"port,omitempty"` // 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. StatusCode *int `json:"status_code,omitempty"` } // HTTPURLRewriteFilter defines a filter that modifies a request during // forwarding. At most one of these filters may be used on a Route rule. This // MUST NOT be used on the same Route rule as a HTTPRequestRedirect filter. type HTTPURLRewriteFilter struct { // Hostname is the value to be used to replace the Host header value during // forwarding. HostName *string `json:"host_name,omitempty"` // Path is the values to be used to replace the path Path *StringMatch `json:"path,omitempty"` } // HTTPRequestMirror defines configuration for the RequestMirror filter. type HTTPRequestMirror struct { // Backend is the backend handling the requests Backend *Backend `json:"backend,omitempty"` Numerator int32 `json:"numerator,omitempty"` Denominator int32 `json:"denominator,omitempty"` } // ExternalAuthProtocol is the protocol used to communicate with an ext_authz backend. type ExternalAuthProtocol string const ( ExternalAuthProtocolGRPC ExternalAuthProtocol = "GRPC" ExternalAuthProtocolHTTP ExternalAuthProtocol = "HTTP" ) // HTTPExternalAuthFilter defines configuration for an external authorization filter. type HTTPExternalAuthFilter struct { // Backend is the authorization service backend. Backend Backend `json:"backend"` // Protocol is the protocol used to communicate with the auth backend. Protocol ExternalAuthProtocol `json:"protocol"` // PathPrefix is prepended to the request path when forwarding to HTTP auth backends. PathPrefix string `json:"path_prefix,omitempty"` // AllowedRequestHeaders are additional headers forwarded to the auth service (HTTP protocol). AllowedRequestHeaders []string `json:"allowed_request_headers,omitempty"` // AllowedResponseHeaders are headers from the auth response to forward to the upstream (HTTP protocol). AllowedResponseHeaders []string `json:"allowed_response_headers,omitempty"` // ForwardBody configures buffering and forwarding of the client request body to the auth service. // If nil or MaxSize is 0, the body is not forwarded. ForwardBody *ForwardBodyConfig `json:"forward_body,omitempty"` } // ForwardBodyConfig controls if and how the client request body is forwarded to the auth service. type ForwardBodyConfig struct { // MaxSize is the maximum number of bytes to buffer and forward. If the body exceeds this, // the body is truncated to MaxSize before being sent to the auth service. MaxSize uint32 `json:"max_size"` } // HTTPCORSFilter defines configuration for the CORS filter. type HTTPCORSFilter struct { // AllowOrigins indicates whether the response can be shared with // requested resource from the given `Origin`. AllowOrigins []string `json:"allowOrigins,omitempty"` // AllowCredentials indicates whether the actual cross-origin request // allows to include credentials. AllowCredentials bool `json:"allowCredentials,omitempty"` // AllowMethods indicates which HTTP methods are supported // for accessing the requested resource. AllowMethods []string `json:"allowMethods,omitempty"` // AllowHeaders indicates which HTTP request headers are supported // for accessing the requested resource. AllowHeaders []string `json:"allowHeaders,omitempty"` // ExposeHeaders indicates which HTTP response headers can be exposed // to client-side scripts in response to a cross-origin request. ExposeHeaders []string `json:"exposeHeaders,omitempty"` // MaxAge indicates the duration (in seconds) for the client to cache // the results of a "preflight" request. MaxAge int32 `json:"maxAge,omitempty"` } // HTTPRoute holds all the details needed to route HTTP traffic to a backend. type HTTPRoute struct { Name string `json:"name,omitempty"` // SourceRule identifies the Gateway API HTTPRoute rule and match that // produced this route when rule identity must be preserved internally. SourceRule *HTTPRouteRule `json:"-"` // Hostnames that the route should match Hostnames []string `json:"hostnames,omitempty"` // PathMatch specifies that the HTTPRoute should match a path. PathMatch StringMatch `json:"path_match"` // HeadersMatch specifies that the HTTPRoute should match a set of headers. HeadersMatch []KeyValueMatch `json:"headers_match,omitempty"` // QueryParamsMatch specifies that the HTTPRoute should match a set of query parameters. QueryParamsMatch []KeyValueMatch `json:"query_params_match,omitempty"` Method *string `json:"method,omitempty"` // Backend is the backend handling the requests Backends []Backend `json:"backends,omitempty"` // BackendHTTPFilters can be used to add or remove HTTP BackendHTTPFilters []*BackendHTTPFilter `json:"backend_http_filters,omitempty"` // DirectResponse instructs the proxy to respond directly to the client. DirectResponse *DirectResponse `json:"direct_response,omitempty"` // RequestHeaderFilter can be used to add or remove an HTTP // header from an HTTP request before it is sent to the upstream target. RequestHeaderFilter *HTTPHeaderFilter `json:"request_header_filter,omitempty"` // ResponseHeaderModifier can be used to add or remove an HTTP // header from an HTTP response before it is sent to the client. ResponseHeaderModifier *HTTPHeaderFilter `json:"response_header_modifier,omitempty"` // RequestRedirect defines a schema for a filter that responds to the // request with an HTTP redirection. RequestRedirect *HTTPRequestRedirectFilter `json:"request_redirect,omitempty"` // Rewrite defines a schema for a filter that modifies the URL of the request. Rewrite *HTTPURLRewriteFilter `json:"rewrite,omitempty"` // RequestMirrors defines a schema for a filter that mirrors HTTP requests // Unlike other filter, multiple request mirrors are supported RequestMirrors []*HTTPRequestMirror `json:"request_mirrors,omitempty"` // ExternalAuth configures external authorization for this route. ExternalAuth *HTTPExternalAuthFilter `json:"external_auth,omitempty"` // IsGRPC is an indicator if this route is related to GRPC IsGRPC bool `json:"is_grpc,omitempty"` // Timeout holds the timeout configuration for a route. Timeout Timeout `json:"timeout"` // Retry holds the retry configuration for a route. Retry *HTTPRetry `json:"retry,omitempty"` // CORS holds cross-origin resource sharing filters for a route. CORS *HTTPCORSFilter `json:"cors,omitempty"` } type BackendHTTPFilter struct { // Name is the name of the Backend, the name is having the format of "namespace:name:port" Name string `json:"name,omitempty"` // RequestHeaderFilter can be used to add or remove an HTTP // header from an HTTP request before it is sent to the upstream target. RequestHeaderFilter *HTTPHeaderFilter `json:"request_header_filter,omitempty"` // ResponseHeaderModifier can be used to add or remove an HTTP // header from an HTTP response before it is sent to the client. ResponseHeaderModifier *HTTPHeaderFilter `json:"response_header_modifier,omitempty"` } // Infrastructure holds the labels and annotations configuration, // which will be propagated to LB service. type Infrastructure struct { // Labels is a map of labels to be propagated to LB service. Labels map[string]string // Annotations is a map of annotations to be propagated to LB service. Annotations map[string]string } // GetMatchKey returns the key for this route's request match criteria. func (r *HTTPRoute) GetMatchKey() string { sb := strings.Builder{} if r.Method != nil { sb.WriteString("method:") sb.WriteString(*r.Method) sb.WriteString("|") } sb.WriteString("path:") sb.WriteString(r.PathMatch.String()) sb.WriteString("|") headers := append([]KeyValueMatch(nil), r.HeadersMatch...) sort.Slice(headers, func(i, j int) bool { return headers[i].String() < headers[j].String() }) for _, hm := range headers { sb.WriteString("header:") sb.WriteString(hm.String()) sb.WriteString("|") } queryParams := append([]KeyValueMatch(nil), r.QueryParamsMatch...) sort.Slice(queryParams, func(i, j int) bool { return queryParams[i].String() < queryParams[j].String() }) for _, qm := range queryParams { sb.WriteString("query:") sb.WriteString(qm.String()) sb.WriteString("|") } if r.RequestRedirect != nil && r.RequestRedirect.Scheme != nil { sb.WriteString("redirect:") sb.WriteString("true") sb.WriteString("|") } if r.ExternalAuth != nil { sb.WriteString("auth:") sb.WriteString(string(r.ExternalAuth.Protocol)) sb.WriteString(":") sb.WriteString(r.ExternalAuth.Backend.Namespace) sb.WriteString(":") sb.WriteString(r.ExternalAuth.Backend.Name) if r.ExternalAuth.Backend.Port != nil { sb.WriteString(":") sb.WriteString(r.ExternalAuth.Backend.Port.GetPort()) } sb.WriteString("|") } return sb.String() } // GetBackendAggregationKey returns the key used to group backend actions into a // single Envoy route. Gateway API routes use rule identity so identical matches // from different rules remain separate and retain rule precedence. Legacy // callers without rule identity keep the existing match-key aggregation. func (r *HTTPRoute) GetBackendAggregationKey() string { if r.SourceRule == nil { return r.GetMatchKey() } return r.SourceRule.key() } // TLSPassthroughRoute holds all the details needed to route TLS traffic to a backend. type TLSPassthroughRoute struct { Name string `json:"name,omitempty"` // Hostnames that the route should match Hostnames []string `json:"hostnames,omitempty"` // Backend is the backend handling the requests Backends []Backend `json:"backends,omitempty"` } // StringMatch describes various types of string matching. // Only one field may be set. // If no fields are set, all paths should match (no path match criteria should // be generated for Envoy.) type StringMatch struct { Prefix string `json:"prefix,omitempty"` Exact string `json:"exact,omitempty"` Regex string `json:"regex,omitempty"` } func (sm StringMatch) String() string { sb := strings.Builder{} if sm.Prefix != "" { sb.WriteString("prefix:") sb.WriteString(sm.Prefix) } else if sm.Exact != "" { sb.WriteString("exact:") sb.WriteString(sm.Exact) } else if sm.Regex != "" { sb.WriteString("regex:") sb.WriteString(sm.Regex) } return sb.String() } type KeyValueMatch struct { Key string `json:"key,omitempty"` Match StringMatch `json:"match"` } func (kv KeyValueMatch) String() string { sb := strings.Builder{} sb.WriteString("kv:") sb.WriteString(kv.Key) sb.WriteString(":") sb.WriteString(kv.Match.String()) return sb.String() } // Backend holds a Kubernetes Service that points to a backend for traffic. type Backend struct { // Name of the Service. Name string `json:"name,omitempty"` // Namespace of the Service. Namespace string `json:"namespace,omitempty"` // Port contains the details of the port on the Service to connect to // If unset, the same port as the top-level Listener will be used. Port *BackendPort `json:"port,omitempty"` // AppProtocol contains the application protocol as per KEP-3726 // for the port of the Service. AppProtocol *string `json:"app_protocol,omitempty"` // TLS specifies details for TLS origination towards this backend. // If unset, TLS must not be originated towards this backend. TLS *BackendTLSOrigination // Weight specifies the percentage of traffic to send to this backend. // This is computed as weight/(sum of all weights in backends) * 100. Weight *int32 `json:"weight,omitempty"` } // BackendPort holds the details of what port on the Service to connect to. // Only one of Port or Name can be set. type BackendPort struct { // Port holds the numeric port to connect to. Port uint32 `json:"port,omitempty"` // Name holds a string which will be used to connect to the port with a // matching spec.ports[].name in the target Service. Name string `json:"name,omitempty"` } // BackendTLSOrigination holds details required to configure TLS origination towards // a backend. type BackendTLSOrigination struct { // CACertRef holds a reference to a CA Certificate. In the initial implementation, // this is usually a ConfigMap, although it could be a Secret as well. // This will probably be converted into a reference to a Secret in the secrets // namespace as part of translation. // // If unset, Envoy should originate TLS, but validate the CA certificate using // whatever certificate chains it already has. CACertRef *FullyQualifiedResource // SNI contains the hostname to be sent as the SNI when TLS is originated. SNI string } // GetPort return the string representation of the port (either the port number or the port name) func (be *BackendPort) GetPort() string { if be.Port != 0 { return strconv.Itoa(int(be.Port)) } return be.Name } // Timeout holds the timeout configuration for a route. type Timeout struct { // Request is the timeout for the request. Request *time.Duration `json:"request,omitempty"` // Backend is the timeout for the backend. Backend *time.Duration `json:"backend,omitempty"` } // HTTPRetry holds the retry configuration for a route. type HTTPRetry struct { // Codes defines the HTTP response status codes for which a backend request // should be retried. Codes []uint32 `json:"codes,omitempty"` // Attempts specifies the maximum number of times an individual request // from the gateway to a backend should be retried. Attempts *int `json:"attempts,omitempty"` // Backoff specifies the minimum duration a Gateway should wait between // retry attempts Backoff *time.Duration `json:"backoff,omitempty"` } // GetServerHeaderTransformation returns the first non-empty server header transformation from HTTP listeners. func (m *Model) GetServerHeaderTransformation() ServerHeaderTransformation { for _, l := range m.HTTP { if l.ServerHeaderTransformation != "" { return l.ServerHeaderTransformation } } return ServerHeaderTransformationOverwrite } // IsEmpty returns true if the model has no HTTP, TLS Passthrough or L4 listeners. func (m *Model) IsEmpty() bool { return len(m.HTTP) == 0 && len(m.TLSPassthrough) == 0 && len(m.L4) == 0 } // IsHTTPListenerConfigured returns true if the model has any HTTP listeners. func (m *Model) IsHTTPListenerConfigured() bool { return len(m.HTTP) > 0 } // IsHTTPSListenerConfigured returns true if the model has any HTTPS listeners. func (m *Model) IsHTTPSListenerConfigured() bool { for _, l := range m.HTTP { if len(l.TLS) > 0 { return true } } return false } // IsL4ListenerConfigured returns true if the model has any L4 listeners. func (m *Model) IsL4ListenerConfigured() bool { return len(m.L4) > 0 } // IsHTTPSPortConfigured returns true if the model contains an HTTPS listener // on the given port number. func (m *Model) IsHTTPSPortConfigured(port uint32) bool { for _, l := range m.HTTP { if len(l.TLS) > 0 && l.Port == port { return true } } return false } // HTTPSPortsSorted returns sorted, unique ports for all HTTPS listeners. func (m *Model) HTTPSPortsSorted() []uint32 { var ports []uint32 for _, l := range m.HTTP { if len(l.TLS) > 0 { ports = append(ports, l.Port) } } return slices.SortedUnique(ports) } // NeedsPerPortHTTPSListeners returns true if the model has more than one distinct HTTPS port. func (m *Model) NeedsPerPortHTTPSListeners() bool { return len(m.HTTPSPortsSorted()) > 1 } // NeedsPerPortTLSPassthroughListeners returns true if the model has more than one distinct TLS passthrough port. func (m *Model) NeedsPerPortTLSPassthroughListeners() bool { return len(m.TLSPassthroughPorts()) > 1 } // NeedsPerPortListeners returns true if any protocol has enough distinct ports // to require per-port Envoy Listener resources, or if cross-protocol SNI overlap // would make a combined listener lose the Gateway listener port boundary. func (m *Model) NeedsPerPortListeners() bool { return m.NeedsPerPortHTTPSListeners() || m.NeedsPerPortTLSPassthroughListeners() || m.NeedsCrossProtocolSplit() } // NeedsCrossProtocolSplit returns true when HTTPS and TLS passthrough filter // chains on different Gateway listener ports cannot safely share a combined // Envoy listener. // // Filter chains from different Gateway listener ports must not share any SNI // match because a combined Envoy listener would otherwise erase the original // Gateway listener port boundary and route traffic for one listener to another. // Same-port HTTPS and TLS passthrough conflicts cannot be fixed by per-port // listeners and need to be rejected before translation. func (m *Model) NeedsCrossProtocolSplit() bool { for _, httpsMatch := range m.httpsFilterChainMatches() { for _, tlsMatch := range m.tlsPassthroughFilterChainMatches() { if httpsMatch.port == tlsMatch.port { continue } if sniHostnamesIntersect(httpsMatch.hostname, tlsMatch.hostname) { return true } } } return false } type filterChainMatch struct { hostname string port uint32 } // httpsFilterChainMatches returns the normalized hostnames and ports that HTTPS // filter chains will use for SNI matching. Each HTTPS filter chain's ServerNames // derive from the listener-level hostname. func (m *Model) httpsFilterChainMatches() []filterChainMatch { var matches []filterChainMatch seen := map[filterChainMatch]struct{}{} for _, l := range m.HTTP { if len(l.TLS) == 0 { continue } match := filterChainMatch{hostname: normalizeHostname(l.Hostname), port: l.Port} if _, ok := seen[match]; ok { continue } seen[match] = struct{}{} matches = append(matches, match) } return matches } // tlsPassthroughFilterChainMatches returns the normalized hostnames and ports // that TLS passthrough filter chains will use for SNI matching. These derive // from route hostnames because each TLS passthrough route generates its own // filter chain. func (m *Model) tlsPassthroughFilterChainMatches() []filterChainMatch { var matches []filterChainMatch seen := map[filterChainMatch]struct{}{} for _, l := range m.TLSPassthrough { for _, r := range l.Routes { if len(r.Hostnames) == 0 { match := filterChainMatch{hostname: allHosts, port: l.Port} if _, ok := seen[match]; !ok { seen[match] = struct{}{} matches = append(matches, match) } continue } for _, h := range r.Hostnames { match := filterChainMatch{hostname: normalizeHostname(h), port: l.Port} if _, ok := seen[match]; ok { continue } seen[match] = struct{}{} matches = append(matches, match) } } } return matches } // IsTLSPassthroughListenerConfigured returns true if the model has any TLS Passthrough listeners. func (m *Model) IsTLSPassthroughListenerConfigured() bool { for _, l := range m.TLSPassthrough { if len(l.Routes) > 0 { return true } } return false } // HTTPPorts returns a list of unique ports for all HTTP listeners. func (m *Model) HTTPPorts() []uint32 { var ports []uint32 for _, l := range m.HTTP { ports = append(ports, l.Port) } return slices.SortedUnique(ports) } // IsCORSFilterConfigured returns true if any HTTP route has a configured CORS filter. func (m *Model) IsCORSFilterConfigured() bool { for _, h := range m.HTTP { for _, r := range h.Routes { if r.CORS != nil { return true } } } return false } // IsAccessLogsConfigured returns true if access logging is configured. func (m *Model) IsAccessLogsConfigured() bool { if m == nil || m.Telemetry == nil { return false } for _, accessLogs := range m.Telemetry.AccessLogs { if len(accessLogs) > 0 { return true } } return false } // IsHTTPAccessLogsConfigured returns true if HTTP access logging is configured. func (m *Model) IsHTTPAccessLogsConfigured() bool { if m == nil || m.Telemetry == nil { return false } return len(m.Telemetry.AccessLogs[AccessLogsTargetHTTP]) > 0 } // IsTCPAccessLogsConfigured returns true if TCP access logging is configured. func (m *Model) IsTCPAccessLogsConfigured() bool { if m == nil || m.Telemetry == nil { return false } return len(m.Telemetry.AccessLogs[AccessLogsTargetTCP]) > 0 } // TLSPassthroughPorts returns a list of unique ports for all TLS Passthrough listeners. func (m *Model) TLSPassthroughPorts() []uint32 { var ports []uint32 for _, l := range m.TLSPassthrough { if len(l.Routes) > 0 { ports = append(ports, l.Port) } } return slices.SortedUnique(ports) } // AllPorts returns a list of unique ports for all listeners. func (m *Model) AllPorts() []uint32 { var ports []uint32 ports = append(ports, m.HTTPPorts()...) ports = append(ports, m.TLSPassthroughPorts()...) return slices.SortedUnique(ports) } // TLSSecretsToHostnames returns a map of TLS secrets to hostnames. // This is only for HTTP listeners. func (m *Model) TLSSecretsToHostnames() map[TLSSecret][]string { res := make(map[TLSSecret][]string) for _, h := range m.HTTP { for _, s := range h.TLS { res[s] = append(res[s], h.Hostname) } } return res } // TLSListenerRef records a (hostname, port) pair for an HTTPS listener. type TLSListenerRef struct { Hostname string Port uint32 } // TLSSecretsToListeners returns, for each TLS secret, the set of // (hostname, port) pairs of all HTTPS listeners that reference it. func (m *Model) TLSSecretsToListeners() map[TLSSecret][]TLSListenerRef { res := make(map[TLSSecret][]TLSListenerRef) for _, l := range m.HTTP { for _, s := range l.TLS { res[s] = append(res[s], TLSListenerRef{Hostname: l.Hostname, Port: l.Port}) } } return res }