google.golang.org/grpc@v1.74.2/xds/internal/xdsclient/xdsresource/unmarshal_cds.go (about) 1 /* 2 * 3 * Copyright 2021 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package xdsresource 19 20 import ( 21 "encoding/json" 22 "errors" 23 "fmt" 24 "net" 25 "strconv" 26 "strings" 27 "time" 28 29 v3clusterpb "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" 30 v3corepb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" 31 v3aggregateclusterpb "github.com/envoyproxy/go-control-plane/envoy/extensions/clusters/aggregate/v3" 32 v3tlspb "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" 33 34 "google.golang.org/grpc/internal/envconfig" 35 "google.golang.org/grpc/internal/pretty" 36 iserviceconfig "google.golang.org/grpc/internal/serviceconfig" 37 "google.golang.org/grpc/internal/xds/bootstrap" 38 "google.golang.org/grpc/internal/xds/matcher" 39 "google.golang.org/grpc/xds/internal/xdsclient/xdslbregistry" 40 "google.golang.org/grpc/xds/internal/xdsclient/xdsresource/version" 41 "google.golang.org/protobuf/proto" 42 "google.golang.org/protobuf/types/known/anypb" 43 "google.golang.org/protobuf/types/known/structpb" 44 ) 45 46 // ValidateClusterAndConstructClusterUpdateForTesting exports the 47 // validateClusterAndConstructClusterUpdate function for testing purposes. 48 var ValidateClusterAndConstructClusterUpdateForTesting = validateClusterAndConstructClusterUpdate 49 50 // TransportSocket proto message has a `name` field which is expected to be set 51 // to this value by the management server. 52 const transportSocketName = "envoy.transport_sockets.tls" 53 54 func unmarshalClusterResource(r *anypb.Any, serverCfg *bootstrap.ServerConfig) (string, ClusterUpdate, error) { 55 r, err := UnwrapResource(r) 56 if err != nil { 57 return "", ClusterUpdate{}, fmt.Errorf("failed to unwrap resource: %v", err) 58 } 59 60 if !IsClusterResource(r.GetTypeUrl()) { 61 return "", ClusterUpdate{}, fmt.Errorf("unexpected resource type: %q ", r.GetTypeUrl()) 62 } 63 64 cluster := &v3clusterpb.Cluster{} 65 if err := proto.Unmarshal(r.GetValue(), cluster); err != nil { 66 return "", ClusterUpdate{}, fmt.Errorf("failed to unmarshal resource: %v", err) 67 } 68 cu, err := validateClusterAndConstructClusterUpdate(cluster, serverCfg) 69 if err != nil { 70 return cluster.GetName(), ClusterUpdate{}, err 71 } 72 cu.Raw = r 73 74 return cluster.GetName(), cu, nil 75 } 76 77 const ( 78 defaultRingHashMinSize = 1024 79 defaultRingHashMaxSize = 8 * 1024 * 1024 // 8M 80 ringHashSizeUpperBound = 8 * 1024 * 1024 // 8M 81 82 defaultLeastRequestChoiceCount = 2 83 ) 84 85 func validateClusterAndConstructClusterUpdate(cluster *v3clusterpb.Cluster, serverCfg *bootstrap.ServerConfig) (ClusterUpdate, error) { 86 telemetryLabels := make(map[string]string) 87 if fmd := cluster.GetMetadata().GetFilterMetadata(); fmd != nil { 88 if val, ok := fmd["com.google.csm.telemetry_labels"]; ok { 89 if fields := val.GetFields(); fields != nil { 90 if val, ok := fields["service_name"]; ok { 91 if _, ok := val.GetKind().(*structpb.Value_StringValue); ok { 92 telemetryLabels["csm.service_name"] = val.GetStringValue() 93 } 94 } 95 if val, ok := fields["service_namespace"]; ok { 96 if _, ok := val.GetKind().(*structpb.Value_StringValue); ok { 97 telemetryLabels["csm.service_namespace_name"] = val.GetStringValue() 98 } 99 } 100 } 101 } 102 } 103 // "The values for the service labels csm.service_name and 104 // csm.service_namespace_name come from xDS, “unknown” if not present." - 105 // CSM Design. 106 if _, ok := telemetryLabels["csm.service_name"]; !ok { 107 telemetryLabels["csm.service_name"] = "unknown" 108 } 109 if _, ok := telemetryLabels["csm.service_namespace_name"]; !ok { 110 telemetryLabels["csm.service_namespace_name"] = "unknown" 111 } 112 113 var lbPolicy json.RawMessage 114 var err error 115 switch cluster.GetLbPolicy() { 116 case v3clusterpb.Cluster_ROUND_ROBIN: 117 lbPolicy = []byte(`[{"xds_wrr_locality_experimental": {"childPolicy": [{"round_robin": {}}]}}]`) 118 case v3clusterpb.Cluster_RING_HASH: 119 rhc := cluster.GetRingHashLbConfig() 120 if rhc.GetHashFunction() != v3clusterpb.Cluster_RingHashLbConfig_XX_HASH { 121 return ClusterUpdate{}, fmt.Errorf("unsupported ring_hash hash function %v in response: %+v", rhc.GetHashFunction(), cluster) 122 } 123 // Minimum defaults to 1024 entries, and limited to 8M entries Maximum 124 // defaults to 8M entries, and limited to 8M entries 125 var minSize, maxSize uint64 = defaultRingHashMinSize, defaultRingHashMaxSize 126 if min := rhc.GetMinimumRingSize(); min != nil { 127 minSize = min.GetValue() 128 } 129 if max := rhc.GetMaximumRingSize(); max != nil { 130 maxSize = max.GetValue() 131 } 132 133 rhLBCfg := []byte(fmt.Sprintf("{\"minRingSize\": %d, \"maxRingSize\": %d}", minSize, maxSize)) 134 lbPolicy = []byte(fmt.Sprintf(`[{"ring_hash_experimental": %s}]`, rhLBCfg)) 135 case v3clusterpb.Cluster_LEAST_REQUEST: 136 // "The configuration for the Least Request LB policy is the 137 // least_request_lb_config field. The field is optional; if not present, 138 // defaults will be assumed for all of its values." - A48 139 lr := cluster.GetLeastRequestLbConfig() 140 var choiceCount uint32 = defaultLeastRequestChoiceCount 141 if cc := lr.GetChoiceCount(); cc != nil { 142 choiceCount = cc.GetValue() 143 } 144 // "If choice_count < 2, the config will be rejected." - A48 145 if choiceCount < 2 { 146 return ClusterUpdate{}, fmt.Errorf("Cluster_LeastRequestLbConfig.ChoiceCount must be >= 2, got: %v", choiceCount) 147 } 148 149 lrLBCfg := []byte(fmt.Sprintf("{\"choiceCount\": %d}", choiceCount)) 150 lbPolicy = []byte(fmt.Sprintf(`[{"least_request_experimental": %s}]`, lrLBCfg)) 151 default: 152 return ClusterUpdate{}, fmt.Errorf("unexpected lbPolicy %v in response: %+v", cluster.GetLbPolicy(), cluster) 153 } 154 // Process security configuration received from the control plane iff the 155 // corresponding environment variable is set. 156 var sc *SecurityConfig 157 if sc, err = securityConfigFromCluster(cluster); err != nil { 158 return ClusterUpdate{}, err 159 } 160 161 // Process outlier detection received from the control plane iff the 162 // corresponding environment variable is set. 163 var od json.RawMessage 164 if od, err = outlierConfigFromCluster(cluster); err != nil { 165 return ClusterUpdate{}, err 166 } 167 168 if cluster.GetLoadBalancingPolicy() != nil { 169 lbPolicy, err = xdslbregistry.ConvertToServiceConfig(cluster.GetLoadBalancingPolicy(), 0) 170 if err != nil { 171 return ClusterUpdate{}, fmt.Errorf("error converting LoadBalancingPolicy %v in response: %+v: %v", cluster.GetLoadBalancingPolicy(), cluster, err) 172 } 173 // "It will be the responsibility of the XdsClient to validate the 174 // converted configuration. It will do this by having the gRPC LB policy 175 // registry parse the configuration." - A52 176 bc := &iserviceconfig.BalancerConfig{} 177 if err := json.Unmarshal(lbPolicy, bc); err != nil { 178 return ClusterUpdate{}, fmt.Errorf("JSON generated from xDS LB policy registry: %s is invalid: %v", pretty.FormatJSON(lbPolicy), err) 179 } 180 } 181 182 ret := ClusterUpdate{ 183 ClusterName: cluster.GetName(), 184 SecurityCfg: sc, 185 MaxRequests: circuitBreakersFromCluster(cluster), 186 LBPolicy: lbPolicy, 187 OutlierDetection: od, 188 TelemetryLabels: telemetryLabels, 189 } 190 191 if lrs := cluster.GetLrsServer(); lrs != nil { 192 if lrs.GetSelf() == nil { 193 return ClusterUpdate{}, fmt.Errorf("unsupported config_source_specifier %T in lrs_server field", lrs.ConfigSourceSpecifier) 194 } 195 ret.LRSServerConfig = serverCfg 196 } 197 198 // Validate and set cluster type from the response. 199 switch { 200 case cluster.GetType() == v3clusterpb.Cluster_EDS: 201 if configsource := cluster.GetEdsClusterConfig().GetEdsConfig(); configsource.GetAds() == nil && configsource.GetSelf() == nil { 202 return ClusterUpdate{}, fmt.Errorf("CDS's EDS config source is not ADS or Self: %+v", cluster) 203 } 204 ret.ClusterType = ClusterTypeEDS 205 ret.EDSServiceName = cluster.GetEdsClusterConfig().GetServiceName() 206 if strings.HasPrefix(ret.ClusterName, "xdstp:") && ret.EDSServiceName == "" { 207 return ClusterUpdate{}, fmt.Errorf("CDS's EDS service name is not set with a new-style cluster name: %+v", cluster) 208 } 209 return ret, nil 210 case cluster.GetType() == v3clusterpb.Cluster_LOGICAL_DNS: 211 ret.ClusterType = ClusterTypeLogicalDNS 212 dnsHN, err := dnsHostNameFromCluster(cluster) 213 if err != nil { 214 return ClusterUpdate{}, err 215 } 216 ret.DNSHostName = dnsHN 217 return ret, nil 218 case cluster.GetClusterType() != nil && cluster.GetClusterType().Name == "envoy.clusters.aggregate": 219 clusters := &v3aggregateclusterpb.ClusterConfig{} 220 if err := proto.Unmarshal(cluster.GetClusterType().GetTypedConfig().GetValue(), clusters); err != nil { 221 return ClusterUpdate{}, fmt.Errorf("failed to unmarshal resource: %v", err) 222 } 223 if len(clusters.Clusters) == 0 { 224 return ClusterUpdate{}, fmt.Errorf("xds: aggregate cluster has empty clusters field in response: %+v", cluster) 225 } 226 ret.ClusterType = ClusterTypeAggregate 227 ret.PrioritizedClusterNames = clusters.Clusters 228 return ret, nil 229 default: 230 return ClusterUpdate{}, fmt.Errorf("unsupported cluster type (%v, %v) in response: %+v", cluster.GetType(), cluster.GetClusterType(), cluster) 231 } 232 } 233 234 // dnsHostNameFromCluster extracts the DNS host name from the cluster's load 235 // assignment. 236 // 237 // There should be exactly one locality, with one endpoint, whose address 238 // contains the address and port. 239 func dnsHostNameFromCluster(cluster *v3clusterpb.Cluster) (string, error) { 240 loadAssignment := cluster.GetLoadAssignment() 241 if loadAssignment == nil { 242 return "", fmt.Errorf("load_assignment not present for LOGICAL_DNS cluster") 243 } 244 if len(loadAssignment.GetEndpoints()) != 1 { 245 return "", fmt.Errorf("load_assignment for LOGICAL_DNS cluster must have exactly one locality, got: %+v", loadAssignment) 246 } 247 endpoints := loadAssignment.GetEndpoints()[0].GetLbEndpoints() 248 if len(endpoints) != 1 { 249 return "", fmt.Errorf("locality for LOGICAL_DNS cluster must have exactly one endpoint, got: %+v", endpoints) 250 } 251 endpoint := endpoints[0].GetEndpoint() 252 if endpoint == nil { 253 return "", fmt.Errorf("endpoint for LOGICAL_DNS cluster not set") 254 } 255 socketAddr := endpoint.GetAddress().GetSocketAddress() 256 if socketAddr == nil { 257 return "", fmt.Errorf("socket address for endpoint for LOGICAL_DNS cluster not set") 258 } 259 if socketAddr.GetResolverName() != "" { 260 return "", fmt.Errorf("socket address for endpoint for LOGICAL_DNS cluster not set has unexpected custom resolver name: %v", socketAddr.GetResolverName()) 261 } 262 host := socketAddr.GetAddress() 263 if host == "" { 264 return "", fmt.Errorf("host for endpoint for LOGICAL_DNS cluster not set") 265 } 266 port := socketAddr.GetPortValue() 267 if port == 0 { 268 return "", fmt.Errorf("port for endpoint for LOGICAL_DNS cluster not set") 269 } 270 return net.JoinHostPort(host, strconv.Itoa(int(port))), nil 271 } 272 273 // securityConfigFromCluster extracts the relevant security configuration from 274 // the received Cluster resource. 275 func securityConfigFromCluster(cluster *v3clusterpb.Cluster) (*SecurityConfig, error) { 276 if tsm := cluster.GetTransportSocketMatches(); len(tsm) != 0 { 277 return nil, fmt.Errorf("unsupported transport_socket_matches field is non-empty: %+v", tsm) 278 } 279 // The Cluster resource contains a `transport_socket` field, which contains 280 // a oneof `typed_config` field of type `protobuf.Any`. The any proto 281 // contains a marshaled representation of an `UpstreamTlsContext` message. 282 ts := cluster.GetTransportSocket() 283 if ts == nil { 284 return nil, nil 285 } 286 if name := ts.GetName(); name != transportSocketName { 287 return nil, fmt.Errorf("transport_socket field has unexpected name: %s", name) 288 } 289 tc := ts.GetTypedConfig() 290 if tc == nil || tc.TypeUrl != version.V3UpstreamTLSContextURL { 291 return nil, fmt.Errorf("transport_socket field has unexpected typeURL: %s", tc.TypeUrl) 292 } 293 upstreamCtx := &v3tlspb.UpstreamTlsContext{} 294 if err := proto.Unmarshal(tc.GetValue(), upstreamCtx); err != nil { 295 return nil, fmt.Errorf("failed to unmarshal UpstreamTlsContext in CDS response: %v", err) 296 } 297 // The following fields from `UpstreamTlsContext` are ignored: 298 // - sni 299 // - allow_renegotiation 300 // - max_session_keys 301 if upstreamCtx.GetCommonTlsContext() == nil { 302 return nil, errors.New("UpstreamTlsContext in CDS response does not contain a CommonTlsContext") 303 } 304 305 return securityConfigFromCommonTLSContext(upstreamCtx.GetCommonTlsContext(), false) 306 } 307 308 // common is expected to be not nil. 309 // The `alpn_protocols` field is ignored. 310 func securityConfigFromCommonTLSContext(common *v3tlspb.CommonTlsContext, server bool) (*SecurityConfig, error) { 311 if common.GetTlsParams() != nil { 312 return nil, fmt.Errorf("unsupported tls_params field in CommonTlsContext message: %+v", common) 313 } 314 if common.GetCustomHandshaker() != nil { 315 return nil, fmt.Errorf("unsupported custom_handshaker field in CommonTlsContext message: %+v", common) 316 } 317 318 // For now, if we can't get a valid security config from the new fields, we 319 // fallback to the old deprecated fields. 320 // TODO: Drop support for deprecated fields. NACK if err != nil here. 321 sc, err1 := securityConfigFromCommonTLSContextUsingNewFields(common, server) 322 if sc == nil || sc.Equal(&SecurityConfig{}) { 323 var err error 324 sc, err = securityConfigFromCommonTLSContextWithDeprecatedFields(common, server) 325 if err != nil { 326 // Retain the validation error from using the new fields. 327 return nil, errors.Join(err1, fmt.Errorf("failed to parse config using deprecated fields: %v", err)) 328 } 329 } 330 if sc != nil { 331 // sc == nil is a valid case where the control plane has not sent us any 332 // security configuration. xDS creds will use fallback creds. 333 if server { 334 if sc.IdentityInstanceName == "" { 335 return nil, errors.New("security configuration on the server-side does not contain identity certificate provider instance name") 336 } 337 } else { 338 if !sc.UseSystemRootCerts && sc.RootInstanceName == "" { 339 return nil, errors.New("security configuration on the client-side does not contain root certificate provider instance name") 340 } 341 } 342 } 343 return sc, nil 344 } 345 346 func securityConfigFromCommonTLSContextWithDeprecatedFields(common *v3tlspb.CommonTlsContext, server bool) (*SecurityConfig, error) { 347 // The `CommonTlsContext` contains a 348 // `tls_certificate_certificate_provider_instance` field of type 349 // `CertificateProviderInstance`, which contains the provider instance name 350 // and the certificate name to fetch identity certs. 351 sc := &SecurityConfig{} 352 if identity := common.GetTlsCertificateCertificateProviderInstance(); identity != nil { 353 sc.IdentityInstanceName = identity.GetInstanceName() 354 sc.IdentityCertName = identity.GetCertificateName() 355 } 356 357 // The `CommonTlsContext` contains a `validation_context_type` field which 358 // is a oneof. We can get the values that we are interested in from two of 359 // those possible values: 360 // - combined validation context: 361 // - contains a default validation context which holds the list of 362 // matchers for accepted SANs. 363 // - contains certificate provider instance configuration 364 // - certificate provider instance configuration 365 // - in this case, we do not get a list of accepted SANs. 366 switch t := common.GetValidationContextType().(type) { 367 case *v3tlspb.CommonTlsContext_CombinedValidationContext: 368 combined := common.GetCombinedValidationContext() 369 var matchers []matcher.StringMatcher 370 if def := combined.GetDefaultValidationContext(); def != nil { 371 for _, m := range def.GetMatchSubjectAltNames() { 372 matcher, err := matcher.StringMatcherFromProto(m) 373 if err != nil { 374 return nil, err 375 } 376 matchers = append(matchers, matcher) 377 } 378 } 379 if server && len(matchers) != 0 { 380 return nil, fmt.Errorf("match_subject_alt_names field in validation context is not supported on the server: %v", common) 381 } 382 sc.SubjectAltNameMatchers = matchers 383 if pi := combined.GetValidationContextCertificateProviderInstance(); pi != nil { 384 sc.RootInstanceName = pi.GetInstanceName() 385 sc.RootCertName = pi.GetCertificateName() 386 } 387 case *v3tlspb.CommonTlsContext_ValidationContextCertificateProviderInstance: 388 pi := common.GetValidationContextCertificateProviderInstance() 389 sc.RootInstanceName = pi.GetInstanceName() 390 sc.RootCertName = pi.GetCertificateName() 391 case nil: 392 // It is valid for the validation context to be nil on the server side. 393 default: 394 return nil, fmt.Errorf("validation context contains unexpected type: %T", t) 395 } 396 return sc, nil 397 } 398 399 // gRFC A29 https://github.com/grpc/proposal/blob/master/A29-xds-tls-security.md 400 // specifies the new way to fetch security configuration and says the following: 401 // 402 // Although there are various ways to obtain certificates as per this proto 403 // (which are supported by Envoy), gRPC supports only one of them and that is 404 // the `CertificateProviderPluginInstance` proto. 405 // 406 // This helper function attempts to fetch security configuration from the 407 // `CertificateProviderPluginInstance` message, given a CommonTlsContext. 408 func securityConfigFromCommonTLSContextUsingNewFields(common *v3tlspb.CommonTlsContext, server bool) (*SecurityConfig, error) { 409 // The `tls_certificate_provider_instance` field of type 410 // `CertificateProviderPluginInstance` is used to fetch the identity 411 // certificate provider. 412 sc := &SecurityConfig{} 413 identity := common.GetTlsCertificateProviderInstance() 414 if identity == nil && len(common.GetTlsCertificates()) != 0 { 415 return nil, fmt.Errorf("expected field tls_certificate_provider_instance is not set, while unsupported field tls_certificates is set in CommonTlsContext message: %+v", common) 416 } 417 if identity == nil && common.GetTlsCertificateSdsSecretConfigs() != nil { 418 return nil, fmt.Errorf("expected field tls_certificate_provider_instance is not set, while unsupported field tls_certificate_sds_secret_configs is set in CommonTlsContext message: %+v", common) 419 } 420 sc.IdentityInstanceName = identity.GetInstanceName() 421 sc.IdentityCertName = identity.GetCertificateName() 422 423 // The `CommonTlsContext` contains a oneof field `validation_context_type`, 424 // which contains the `CertificateValidationContext` message in one of the 425 // following ways: 426 // - `validation_context` field 427 // - this is directly of type `CertificateValidationContext` 428 // - `combined_validation_context` field 429 // - this is of type `CombinedCertificateValidationContext` and contains 430 // a `default validation context` field of type 431 // `CertificateValidationContext` 432 // 433 // The `CertificateValidationContext` message has the following fields that 434 // we are interested in: 435 // - `ca_certificate_provider_instance` 436 // - this is of type `CertificateProviderPluginInstance` 437 // - `system_root_certs`: 438 // - This indicates the usage of system root certs for validation. 439 // - `match_subject_alt_names` 440 // - this is a list of string matchers 441 // 442 // The `CertificateProviderPluginInstance` message contains two fields 443 // - instance_name 444 // - this is the certificate provider instance name to be looked up in 445 // the bootstrap configuration 446 // - certificate_name 447 // - this is an opaque name passed to the certificate provider 448 var validationCtx *v3tlspb.CertificateValidationContext 449 switch typ := common.GetValidationContextType().(type) { 450 case *v3tlspb.CommonTlsContext_ValidationContext: 451 validationCtx = common.GetValidationContext() 452 case *v3tlspb.CommonTlsContext_CombinedValidationContext: 453 validationCtx = common.GetCombinedValidationContext().GetDefaultValidationContext() 454 case nil: 455 // It is valid for the validation context to be nil on the server side. 456 return sc, nil 457 default: 458 return nil, fmt.Errorf("validation context contains unexpected type: %T", typ) 459 } 460 // If we get here, it means that the `CertificateValidationContext` message 461 // was found through one of the supported ways. It is an error if the 462 // validation context is specified, but it does not specify a way to 463 // validate TLS certificates. Peer TLS certs can be verified in the 464 // following ways: 465 // 1. If the ca_certificate_provider_instance field is set, it contains 466 // information about the certificate provider to be used for the root 467 // certificates, else 468 // 2. If the system_root_certs field is set, and the config is for a client, 469 // use the system default root certs. 470 useSystemRootCerts := false 471 if validationCtx.GetCaCertificateProviderInstance() == nil && envconfig.XDSSystemRootCertsEnabled { 472 if server { 473 if validationCtx.GetSystemRootCerts() != nil { 474 // The `system_root_certs` field will not be supported on the 475 // gRPC server side. If `ca_certificate_provider_instance` is 476 // unset and `system_root_certs` is set, the LDS resource will 477 // be NACKed. 478 // - A82 479 return nil, fmt.Errorf("expected field ca_certificate_provider_instance is missing and unexpected field system_root_certs is set for server in CommonTlsContext message: %+v", common) 480 } 481 } else { 482 if validationCtx.GetSystemRootCerts() != nil { 483 useSystemRootCerts = true 484 } 485 } 486 } 487 488 // The following fields are ignored: 489 // - trusted_ca 490 // - watched_directory 491 // - allow_expired_certificate 492 // - trust_chain_verification 493 switch { 494 case len(validationCtx.GetVerifyCertificateSpki()) != 0: 495 return nil, fmt.Errorf("unsupported verify_certificate_spki field in CommonTlsContext message: %+v", common) 496 case len(validationCtx.GetVerifyCertificateHash()) != 0: 497 return nil, fmt.Errorf("unsupported verify_certificate_hash field in CommonTlsContext message: %+v", common) 498 case validationCtx.GetRequireSignedCertificateTimestamp().GetValue(): 499 return nil, fmt.Errorf("unsupported require_signed_certificate_timestamp field in CommonTlsContext message: %+v", common) 500 case validationCtx.GetCrl() != nil: 501 return nil, fmt.Errorf("unsupported crl field in CommonTlsContext message: %+v", common) 502 case validationCtx.GetCustomValidatorConfig() != nil: 503 return nil, fmt.Errorf("unsupported custom_validator_config field in CommonTlsContext message: %+v", common) 504 } 505 506 if rootProvider := validationCtx.GetCaCertificateProviderInstance(); rootProvider != nil { 507 sc.RootInstanceName = rootProvider.GetInstanceName() 508 sc.RootCertName = rootProvider.GetCertificateName() 509 } else if useSystemRootCerts { 510 sc.UseSystemRootCerts = true 511 } else if !server && envconfig.XDSSystemRootCertsEnabled { 512 return nil, fmt.Errorf("expected fields ca_certificate_provider_instance and system_root_certs are missing in CommonTlsContext message: %+v", common) 513 } else { 514 // Don't mention the system_root_certs field if it was not checked. 515 return nil, fmt.Errorf("expected field ca_certificate_provider_instance is missing in CommonTlsContext message: %+v", common) 516 } 517 518 var matchers []matcher.StringMatcher 519 for _, m := range validationCtx.GetMatchSubjectAltNames() { 520 matcher, err := matcher.StringMatcherFromProto(m) 521 if err != nil { 522 return nil, err 523 } 524 matchers = append(matchers, matcher) 525 } 526 if server && len(matchers) != 0 { 527 return nil, fmt.Errorf("match_subject_alt_names field in validation context is not supported on the server: %v", common) 528 } 529 sc.SubjectAltNameMatchers = matchers 530 return sc, nil 531 } 532 533 // circuitBreakersFromCluster extracts the circuit breakers configuration from 534 // the received cluster resource. Returns nil if no CircuitBreakers or no 535 // Thresholds in CircuitBreakers. 536 func circuitBreakersFromCluster(cluster *v3clusterpb.Cluster) *uint32 { 537 for _, threshold := range cluster.GetCircuitBreakers().GetThresholds() { 538 if threshold.GetPriority() != v3corepb.RoutingPriority_DEFAULT { 539 continue 540 } 541 maxRequestsPb := threshold.GetMaxRequests() 542 if maxRequestsPb == nil { 543 return nil 544 } 545 maxRequests := maxRequestsPb.GetValue() 546 return &maxRequests 547 } 548 return nil 549 } 550 551 // idurationp takes a time.Duration and converts it to an internal duration, and 552 // returns a pointer to that internal duration. 553 func idurationp(d time.Duration) *iserviceconfig.Duration { 554 id := iserviceconfig.Duration(d) 555 return &id 556 } 557 558 func uint32p(i uint32) *uint32 { 559 return &i 560 } 561 562 // Helper types to prepare Outlier Detection JSON. Pointer types to distinguish 563 // between unset and a zero value. 564 type successRateEjection struct { 565 StdevFactor *uint32 `json:"stdevFactor,omitempty"` 566 EnforcementPercentage *uint32 `json:"enforcementPercentage,omitempty"` 567 MinimumHosts *uint32 `json:"minimumHosts,omitempty"` 568 RequestVolume *uint32 `json:"requestVolume,omitempty"` 569 } 570 571 type failurePercentageEjection struct { 572 Threshold *uint32 `json:"threshold,omitempty"` 573 EnforcementPercentage *uint32 `json:"enforcementPercentage,omitempty"` 574 MinimumHosts *uint32 `json:"minimumHosts,omitempty"` 575 RequestVolume *uint32 `json:"requestVolume,omitempty"` 576 } 577 578 type odLBConfig struct { 579 Interval *iserviceconfig.Duration `json:"interval,omitempty"` 580 BaseEjectionTime *iserviceconfig.Duration `json:"baseEjectionTime,omitempty"` 581 MaxEjectionTime *iserviceconfig.Duration `json:"maxEjectionTime,omitempty"` 582 MaxEjectionPercent *uint32 `json:"maxEjectionPercent,omitempty"` 583 SuccessRateEjection *successRateEjection `json:"successRateEjection,omitempty"` 584 FailurePercentageEjection *failurePercentageEjection `json:"failurePercentageEjection,omitempty"` 585 } 586 587 // outlierConfigFromCluster converts the received Outlier Detection 588 // configuration into JSON configuration for Outlier Detection, taking into 589 // account xDS Defaults. Returns nil if no OutlierDetection field set in the 590 // cluster resource. 591 func outlierConfigFromCluster(cluster *v3clusterpb.Cluster) (json.RawMessage, error) { 592 od := cluster.GetOutlierDetection() 593 if od == nil { 594 return nil, nil 595 } 596 597 // "The outlier_detection field of the Cluster resource should have its fields 598 // validated according to the rules for the corresponding LB policy config 599 // fields in the above "Validation" section. If any of these requirements is 600 // violated, the Cluster resource should be NACKed." - A50 601 // "The google.protobuf.Duration fields interval, base_ejection_time, and 602 // max_ejection_time must obey the restrictions in the 603 // google.protobuf.Duration documentation and they must have non-negative 604 // values." - A50 605 var interval *iserviceconfig.Duration 606 if i := od.GetInterval(); i != nil { 607 if err := i.CheckValid(); err != nil { 608 return nil, fmt.Errorf("outlier_detection.interval is invalid with error: %v", err) 609 } 610 if interval = idurationp(i.AsDuration()); *interval < 0 { 611 return nil, fmt.Errorf("outlier_detection.interval = %v; must be a valid duration and >= 0", *interval) 612 } 613 } 614 615 var baseEjectionTime *iserviceconfig.Duration 616 if bet := od.GetBaseEjectionTime(); bet != nil { 617 if err := bet.CheckValid(); err != nil { 618 return nil, fmt.Errorf("outlier_detection.base_ejection_time is invalid with error: %v", err) 619 } 620 if baseEjectionTime = idurationp(bet.AsDuration()); *baseEjectionTime < 0 { 621 return nil, fmt.Errorf("outlier_detection.base_ejection_time = %v; must be >= 0", *baseEjectionTime) 622 } 623 } 624 625 var maxEjectionTime *iserviceconfig.Duration 626 if met := od.GetMaxEjectionTime(); met != nil { 627 if err := met.CheckValid(); err != nil { 628 return nil, fmt.Errorf("outlier_detection.max_ejection_time is invalid: %v", err) 629 } 630 if maxEjectionTime = idurationp(met.AsDuration()); *maxEjectionTime < 0 { 631 return nil, fmt.Errorf("outlier_detection.max_ejection_time = %v; must be >= 0", *maxEjectionTime) 632 } 633 } 634 635 // "The fields max_ejection_percent, enforcing_success_rate, 636 // failure_percentage_threshold, and enforcing_failure_percentage must have 637 // values less than or equal to 100. If any of these requirements is 638 // violated, the Cluster resource should be NACKed." - A50 639 var maxEjectionPercent *uint32 640 if mep := od.GetMaxEjectionPercent(); mep != nil { 641 if maxEjectionPercent = uint32p(mep.GetValue()); *maxEjectionPercent > 100 { 642 return nil, fmt.Errorf("outlier_detection.max_ejection_percent = %v; must be <= 100", *maxEjectionPercent) 643 } 644 } 645 // "if the enforcing_success_rate field is set to 0, the config 646 // success_rate_ejection field will be null and all success_rate_* fields 647 // will be ignored." - A50 648 var enforcingSuccessRate *uint32 649 if esr := od.GetEnforcingSuccessRate(); esr != nil { 650 if enforcingSuccessRate = uint32p(esr.GetValue()); *enforcingSuccessRate > 100 { 651 return nil, fmt.Errorf("outlier_detection.enforcing_success_rate = %v; must be <= 100", *enforcingSuccessRate) 652 } 653 } 654 var failurePercentageThreshold *uint32 655 if fpt := od.GetFailurePercentageThreshold(); fpt != nil { 656 if failurePercentageThreshold = uint32p(fpt.GetValue()); *failurePercentageThreshold > 100 { 657 return nil, fmt.Errorf("outlier_detection.failure_percentage_threshold = %v; must be <= 100", *failurePercentageThreshold) 658 } 659 } 660 // "If the enforcing_failure_percent field is set to 0 or null, the config 661 // failure_percent_ejection field will be null and all failure_percent_* 662 // fields will be ignored." - A50 663 var enforcingFailurePercentage *uint32 664 if efp := od.GetEnforcingFailurePercentage(); efp != nil { 665 if enforcingFailurePercentage = uint32p(efp.GetValue()); *enforcingFailurePercentage > 100 { 666 return nil, fmt.Errorf("outlier_detection.enforcing_failure_percentage = %v; must be <= 100", *enforcingFailurePercentage) 667 } 668 } 669 670 var successRateStdevFactor *uint32 671 if srsf := od.GetSuccessRateStdevFactor(); srsf != nil { 672 successRateStdevFactor = uint32p(srsf.GetValue()) 673 } 674 var successRateMinimumHosts *uint32 675 if srmh := od.GetSuccessRateMinimumHosts(); srmh != nil { 676 successRateMinimumHosts = uint32p(srmh.GetValue()) 677 } 678 var successRateRequestVolume *uint32 679 if srrv := od.GetSuccessRateRequestVolume(); srrv != nil { 680 successRateRequestVolume = uint32p(srrv.GetValue()) 681 } 682 var failurePercentageMinimumHosts *uint32 683 if fpmh := od.GetFailurePercentageMinimumHosts(); fpmh != nil { 684 failurePercentageMinimumHosts = uint32p(fpmh.GetValue()) 685 } 686 var failurePercentageRequestVolume *uint32 687 if fprv := od.GetFailurePercentageRequestVolume(); fprv != nil { 688 failurePercentageRequestVolume = uint32p(fprv.GetValue()) 689 } 690 691 // "if the enforcing_success_rate field is set to 0, the config 692 // success_rate_ejection field will be null and all success_rate_* fields 693 // will be ignored." - A50 694 var sre *successRateEjection 695 if enforcingSuccessRate == nil || *enforcingSuccessRate != 0 { 696 sre = &successRateEjection{ 697 StdevFactor: successRateStdevFactor, 698 EnforcementPercentage: enforcingSuccessRate, 699 MinimumHosts: successRateMinimumHosts, 700 RequestVolume: successRateRequestVolume, 701 } 702 } 703 704 // "If the enforcing_failure_percent field is set to 0 or null, the config 705 // failure_percent_ejection field will be null and all failure_percent_* 706 // fields will be ignored." - A50 707 var fpe *failurePercentageEjection 708 if enforcingFailurePercentage != nil && *enforcingFailurePercentage != 0 { 709 fpe = &failurePercentageEjection{ 710 Threshold: failurePercentageThreshold, 711 EnforcementPercentage: enforcingFailurePercentage, 712 MinimumHosts: failurePercentageMinimumHosts, 713 RequestVolume: failurePercentageRequestVolume, 714 } 715 } 716 717 odLBCfg := &odLBConfig{ 718 Interval: interval, 719 BaseEjectionTime: baseEjectionTime, 720 MaxEjectionTime: maxEjectionTime, 721 MaxEjectionPercent: maxEjectionPercent, 722 SuccessRateEjection: sre, 723 FailurePercentageEjection: fpe, 724 } 725 return json.Marshal(odLBCfg) 726 }