• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #19778

11 Apr 2025 03:25PM UTC coverage: 88.572% (-0.01%) from 88.586%
#19778

push

github

web-flow
xds: Enable deprecation warnings

The security code referenced fields removed from gRFC A29 before it was
finalized.

Note that this fixes a bug in CommonTlsContextUtil where
CombinedValidationContext was not checked. I believe this was the only
location with such a bug as I audited all non-test usages of
has/getValidationContext() and confirmed they have have a corresponding
has/getCombinedValidationContext().

34707 of 39185 relevant lines covered (88.57%)

0.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.97
/../xds/src/main/java/io/grpc/xds/XdsClusterResource.java
1
/*
2
 * Copyright 2022 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.xds;
18

19
import static com.google.common.base.Preconditions.checkNotNull;
20
import static io.grpc.xds.client.Bootstrapper.ServerInfo;
21

22
import com.google.auto.value.AutoValue;
23
import com.google.common.annotations.VisibleForTesting;
24
import com.google.common.base.MoreObjects;
25
import com.google.common.base.Strings;
26
import com.google.common.collect.ImmutableList;
27
import com.google.common.collect.ImmutableMap;
28
import com.google.protobuf.Duration;
29
import com.google.protobuf.InvalidProtocolBufferException;
30
import com.google.protobuf.Message;
31
import com.google.protobuf.Struct;
32
import com.google.protobuf.util.Durations;
33
import io.envoyproxy.envoy.config.cluster.v3.CircuitBreakers.Thresholds;
34
import io.envoyproxy.envoy.config.cluster.v3.Cluster;
35
import io.envoyproxy.envoy.config.core.v3.RoutingPriority;
36
import io.envoyproxy.envoy.config.core.v3.SocketAddress;
37
import io.envoyproxy.envoy.config.core.v3.TransportSocket;
38
import io.envoyproxy.envoy.config.endpoint.v3.ClusterLoadAssignment;
39
import io.envoyproxy.envoy.extensions.transport_sockets.http_11_proxy.v3.Http11ProxyUpstreamTransport;
40
import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CertificateValidationContext;
41
import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CommonTlsContext;
42
import io.grpc.LoadBalancerRegistry;
43
import io.grpc.NameResolver;
44
import io.grpc.internal.GrpcUtil;
45
import io.grpc.internal.ServiceConfigUtil;
46
import io.grpc.internal.ServiceConfigUtil.LbConfig;
47
import io.grpc.xds.EnvoyServerProtoData.OutlierDetection;
48
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
49
import io.grpc.xds.XdsClusterResource.CdsUpdate;
50
import io.grpc.xds.client.XdsClient.ResourceUpdate;
51
import io.grpc.xds.client.XdsResourceType;
52
import io.grpc.xds.internal.security.CommonTlsContextUtil;
53
import java.util.List;
54
import java.util.Locale;
55
import java.util.Set;
56
import javax.annotation.Nullable;
57

58
class XdsClusterResource extends XdsResourceType<CdsUpdate> {
1✔
59
  @VisibleForTesting
60
  static boolean enableLeastRequest =
61
      !Strings.isNullOrEmpty(System.getenv("GRPC_EXPERIMENTAL_ENABLE_LEAST_REQUEST"))
1✔
62
          ? Boolean.parseBoolean(System.getenv("GRPC_EXPERIMENTAL_ENABLE_LEAST_REQUEST"))
×
63
          : Boolean.parseBoolean(System.getProperty("io.grpc.xds.experimentalEnableLeastRequest"));
1✔
64
  @VisibleForTesting
65
  public static boolean enableSystemRootCerts =
1✔
66
      GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_SYSTEM_ROOT_CERTS", false);
1✔
67
  static boolean isEnabledXdsHttpConnect =
1✔
68
      GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_HTTP_CONNECT", false);
1✔
69

70
  @VisibleForTesting
71
  static final String AGGREGATE_CLUSTER_TYPE_NAME = "envoy.clusters.aggregate";
72
  static final String ADS_TYPE_URL_CDS =
73
      "type.googleapis.com/envoy.config.cluster.v3.Cluster";
74
  private static final String TYPE_URL_CLUSTER_CONFIG =
75
      "type.googleapis.com/envoy.extensions.clusters.aggregate.v3.ClusterConfig";
76
  private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT =
77
      "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext";
78
  private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT_V2 =
79
      "type.googleapis.com/envoy.api.v2.auth.UpstreamTlsContext";
80
  static final String TRANSPORT_SOCKET_NAME_HTTP11_PROXY =
81
      "type.googleapis.com/envoy.extensions.transport_sockets.http_11_proxy.v3"
82
          + ".Http11ProxyUpstreamTransport";
83
  private final LoadBalancerRegistry loadBalancerRegistry
1✔
84
      = LoadBalancerRegistry.getDefaultRegistry();
1✔
85

86
  private static final XdsClusterResource instance = new XdsClusterResource();
1✔
87

88
  public static XdsClusterResource getInstance() {
89
    return instance;
1✔
90
  }
91

92
  @Override
93
  @Nullable
94
  protected String extractResourceName(Message unpackedResource) {
95
    if (!(unpackedResource instanceof Cluster)) {
1✔
96
      return null;
×
97
    }
98
    return ((Cluster) unpackedResource).getName();
1✔
99
  }
100

101
  @Override
102
  public String typeName() {
103
    return "CDS";
1✔
104
  }
105

106
  @Override
107
  public String typeUrl() {
108
    return ADS_TYPE_URL_CDS;
1✔
109
  }
110

111
  @Override
112
  public boolean shouldRetrieveResourceKeysForArgs() {
113
    return true;
1✔
114
  }
115

116
  @Override
117
  protected boolean isFullStateOfTheWorld() {
118
    return true;
1✔
119
  }
120

121
  @Override
122
  @SuppressWarnings("unchecked")
123
  protected Class<Cluster> unpackedClassName() {
124
    return Cluster.class;
1✔
125
  }
126

127
  @Override
128
  protected CdsUpdate doParse(Args args, Message unpackedMessage) throws ResourceInvalidException {
129
    if (!(unpackedMessage instanceof Cluster)) {
1✔
130
      throw new ResourceInvalidException("Invalid message type: " + unpackedMessage.getClass());
×
131
    }
132
    Set<String> certProviderInstances = null;
1✔
133
    if (args.getBootstrapInfo() != null && args.getBootstrapInfo().certProviders() != null) {
1✔
134
      certProviderInstances = args.getBootstrapInfo().certProviders().keySet();
1✔
135
    }
136
    return processCluster((Cluster) unpackedMessage, certProviderInstances,
1✔
137
        args.getServerInfo(), loadBalancerRegistry);
1✔
138
  }
139

140
  @VisibleForTesting
141
  static CdsUpdate processCluster(Cluster cluster,
142
                                  Set<String> certProviderInstances,
143
                                  ServerInfo serverInfo,
144
                                  LoadBalancerRegistry loadBalancerRegistry)
145
      throws ResourceInvalidException {
146
    StructOrError<CdsUpdate.Builder> structOrError;
147
    switch (cluster.getClusterDiscoveryTypeCase()) {
1✔
148
      case TYPE:
149
        structOrError = parseNonAggregateCluster(cluster,
1✔
150
            certProviderInstances, serverInfo);
151
        break;
1✔
152
      case CLUSTER_TYPE:
153
        structOrError = parseAggregateCluster(cluster);
1✔
154
        break;
1✔
155
      case CLUSTERDISCOVERYTYPE_NOT_SET:
156
      default:
157
        throw new ResourceInvalidException(
1✔
158
            "Cluster " + cluster.getName() + ": unspecified cluster discovery type");
1✔
159
    }
160
    if (structOrError.getErrorDetail() != null) {
1✔
161
      throw new ResourceInvalidException(structOrError.getErrorDetail());
1✔
162
    }
163
    CdsUpdate.Builder updateBuilder = structOrError.getStruct();
1✔
164

165
    ImmutableMap<String, ?> lbPolicyConfig = LoadBalancerConfigFactory.newConfig(cluster,
1✔
166
        enableLeastRequest);
167

168
    // Validate the LB config by trying to parse it with the corresponding LB provider.
169
    LbConfig lbConfig = ServiceConfigUtil.unwrapLoadBalancingConfig(lbPolicyConfig);
1✔
170
    NameResolver.ConfigOrError configOrError = loadBalancerRegistry.getProvider(
1✔
171
        lbConfig.getPolicyName()).parseLoadBalancingPolicyConfig(
1✔
172
        lbConfig.getRawConfigValue());
1✔
173
    if (configOrError.getError() != null) {
1✔
174
      throw new ResourceInvalidException(structOrError.getErrorDetail());
×
175
    }
176

177
    updateBuilder.lbPolicyConfig(lbPolicyConfig);
1✔
178
    updateBuilder.filterMetadata(
1✔
179
        ImmutableMap.copyOf(cluster.getMetadata().getFilterMetadataMap()));
1✔
180

181
    try {
182
      MetadataRegistry registry = MetadataRegistry.getInstance();
1✔
183
      ImmutableMap<String, Object> parsedFilterMetadata =
1✔
184
          registry.parseMetadata(cluster.getMetadata());
1✔
185
      updateBuilder.parsedMetadata(parsedFilterMetadata);
1✔
186
    } catch (ResourceInvalidException e) {
×
187
      throw new ResourceInvalidException(
×
188
          "Failed to parse xDS filter metadata for cluster '" + cluster.getName() + "': "
×
189
              + e.getMessage(), e);
×
190
    }
1✔
191

192
    return updateBuilder.build();
1✔
193
  }
194

195
  private static StructOrError<CdsUpdate.Builder> parseAggregateCluster(Cluster cluster) {
196
    String clusterName = cluster.getName();
1✔
197
    Cluster.CustomClusterType customType = cluster.getClusterType();
1✔
198
    String typeName = customType.getName();
1✔
199
    if (!typeName.equals(AGGREGATE_CLUSTER_TYPE_NAME)) {
1✔
200
      return StructOrError.fromError(
×
201
          "Cluster " + clusterName + ": unsupported custom cluster type: " + typeName);
202
    }
203
    io.envoyproxy.envoy.extensions.clusters.aggregate.v3.ClusterConfig clusterConfig;
204
    try {
205
      clusterConfig = unpackCompatibleType(customType.getTypedConfig(),
1✔
206
          io.envoyproxy.envoy.extensions.clusters.aggregate.v3.ClusterConfig.class,
207
          TYPE_URL_CLUSTER_CONFIG, null);
208
    } catch (InvalidProtocolBufferException e) {
×
209
      return StructOrError.fromError("Cluster " + clusterName + ": malformed ClusterConfig: " + e);
×
210
    }
1✔
211
    return StructOrError.fromStruct(CdsUpdate.forAggregate(
1✔
212
        clusterName, clusterConfig.getClustersList()));
1✔
213
  }
214

215
  private static StructOrError<CdsUpdate.Builder> parseNonAggregateCluster(
216
      Cluster cluster, Set<String> certProviderInstances, ServerInfo serverInfo) {
217
    String clusterName = cluster.getName();
1✔
218
    ServerInfo lrsServerInfo = null;
1✔
219
    Long maxConcurrentRequests = null;
1✔
220
    UpstreamTlsContext upstreamTlsContext = null;
1✔
221
    OutlierDetection outlierDetection = null;
1✔
222
    boolean isHttp11ProxyAvailable = false;
1✔
223
    if (cluster.hasLrsServer()) {
1✔
224
      if (!cluster.getLrsServer().hasSelf()) {
1✔
225
        return StructOrError.fromError(
×
226
            "Cluster " + clusterName + ": only support LRS for the same management server");
227
      }
228
      lrsServerInfo = serverInfo;
1✔
229
    }
230
    if (cluster.hasCircuitBreakers()) {
1✔
231
      List<Thresholds> thresholds = cluster.getCircuitBreakers().getThresholdsList();
1✔
232
      for (Thresholds threshold : thresholds) {
1✔
233
        if (threshold.getPriority() != RoutingPriority.DEFAULT) {
1✔
234
          continue;
1✔
235
        }
236
        if (threshold.hasMaxRequests()) {
1✔
237
          maxConcurrentRequests = Integer.toUnsignedLong(threshold.getMaxRequests().getValue());
1✔
238
        }
239
      }
1✔
240
    }
241
    if (cluster.getTransportSocketMatchesCount() > 0) {
1✔
242
      return StructOrError.fromError("Cluster " + clusterName
1✔
243
          + ": transport-socket-matches not supported.");
244
    }
245
    boolean hasTransportSocket = cluster.hasTransportSocket();
1✔
246
    TransportSocket transportSocket = cluster.getTransportSocket();
1✔
247

248
    if (hasTransportSocket && !TRANSPORT_SOCKET_NAME_TLS.equals(transportSocket.getName())
1✔
249
        && !(isEnabledXdsHttpConnect
250
        && TRANSPORT_SOCKET_NAME_HTTP11_PROXY.equals(transportSocket.getName()))) {
1✔
251
      return StructOrError.fromError(
1✔
252
          "transport-socket with name " + transportSocket.getName() + " not supported.");
1✔
253
    }
254

255
    if (hasTransportSocket && isEnabledXdsHttpConnect
1✔
256
        && TRANSPORT_SOCKET_NAME_HTTP11_PROXY.equals(transportSocket.getName())) {
1✔
257
      isHttp11ProxyAvailable = true;
1✔
258
      try {
259
        Http11ProxyUpstreamTransport wrappedTransportSocket = transportSocket
1✔
260
            .getTypedConfig().unpack(io.envoyproxy.envoy.extensions.transport_sockets
1✔
261
                .http_11_proxy.v3.Http11ProxyUpstreamTransport.class);
262
        hasTransportSocket = wrappedTransportSocket.hasTransportSocket();
1✔
263
        transportSocket = wrappedTransportSocket.getTransportSocket();
1✔
264
      } catch (InvalidProtocolBufferException e) {
×
265
        return StructOrError.fromError(
×
266
            "Cluster " + clusterName + ": malformed Http11ProxyUpstreamTransport: " + e);
267
      } catch (ClassCastException e) {
×
268
        return StructOrError.fromError(
×
269
            "Cluster " + clusterName
270
                + ": invalid transport_socket type in Http11ProxyUpstreamTransport");
271
      }
1✔
272
    }
273

274
    if (hasTransportSocket && TRANSPORT_SOCKET_NAME_TLS.equals(transportSocket.getName())) {
1✔
275
      try {
276
        upstreamTlsContext = UpstreamTlsContext.fromEnvoyProtoUpstreamTlsContext(
1✔
277
            validateUpstreamTlsContext(
1✔
278
                unpackCompatibleType(transportSocket.getTypedConfig(),
1✔
279
                    io.envoyproxy.envoy.extensions
280
                        .transport_sockets.tls.v3.UpstreamTlsContext.class,
281
                    TYPE_URL_UPSTREAM_TLS_CONTEXT, TYPE_URL_UPSTREAM_TLS_CONTEXT_V2),
282
                certProviderInstances));
283
      } catch (InvalidProtocolBufferException | ResourceInvalidException e) {
1✔
284
        return StructOrError.fromError(
1✔
285
            "Cluster " + clusterName + ": malformed UpstreamTlsContext: " + e);
286
      }
1✔
287
    }
288

289
    if (cluster.hasOutlierDetection()) {
1✔
290
      try {
291
        outlierDetection = OutlierDetection.fromEnvoyOutlierDetection(
1✔
292
            validateOutlierDetection(cluster.getOutlierDetection()));
1✔
293
      } catch (ResourceInvalidException e) {
1✔
294
        return StructOrError.fromError(
1✔
295
            "Cluster " + clusterName + ": malformed outlier_detection: " + e);
296
      }
1✔
297
    }
298

299
    Cluster.DiscoveryType type = cluster.getType();
1✔
300
    if (type == Cluster.DiscoveryType.EDS) {
1✔
301
      String edsServiceName = null;
1✔
302
      io.envoyproxy.envoy.config.cluster.v3.Cluster.EdsClusterConfig edsClusterConfig =
1✔
303
          cluster.getEdsClusterConfig();
1✔
304
      if (!edsClusterConfig.getEdsConfig().hasAds()
1✔
305
          && ! edsClusterConfig.getEdsConfig().hasSelf()) {
1✔
306
        return StructOrError.fromError(
1✔
307
            "Cluster " + clusterName + ": field eds_cluster_config must be set to indicate to use"
308
                + " EDS over ADS or self ConfigSource");
309
      }
310
      // If the service_name field is set, that value will be used for the EDS request.
311
      if (!edsClusterConfig.getServiceName().isEmpty()) {
1✔
312
        edsServiceName = edsClusterConfig.getServiceName();
1✔
313
      }
314
      // edsServiceName is required if the CDS resource has an xdstp name.
315
      if ((edsServiceName == null) && clusterName.toLowerCase(Locale.ROOT).startsWith("xdstp:")) {
1✔
316
        return StructOrError.fromError(
1✔
317
            "EDS service_name must be set when Cluster resource has an xdstp name");
318
      }
319

320
      return StructOrError.fromStruct(CdsUpdate.forEds(
1✔
321
          clusterName, edsServiceName, lrsServerInfo, maxConcurrentRequests, upstreamTlsContext,
322
          outlierDetection, isHttp11ProxyAvailable));
323
    } else if (type.equals(Cluster.DiscoveryType.LOGICAL_DNS)) {
1✔
324
      if (!cluster.hasLoadAssignment()) {
1✔
325
        return StructOrError.fromError(
×
326
            "Cluster " + clusterName + ": LOGICAL_DNS clusters must have a single host");
327
      }
328
      ClusterLoadAssignment assignment = cluster.getLoadAssignment();
1✔
329
      if (assignment.getEndpointsCount() != 1
1✔
330
          || assignment.getEndpoints(0).getLbEndpointsCount() != 1) {
1✔
331
        return StructOrError.fromError(
×
332
            "Cluster " + clusterName + ": LOGICAL_DNS clusters must have a single "
333
                + "locality_lb_endpoint and a single lb_endpoint");
334
      }
335
      io.envoyproxy.envoy.config.endpoint.v3.LbEndpoint lbEndpoint =
1✔
336
          assignment.getEndpoints(0).getLbEndpoints(0);
1✔
337
      if (!lbEndpoint.hasEndpoint() || !lbEndpoint.getEndpoint().hasAddress()
1✔
338
          || !lbEndpoint.getEndpoint().getAddress().hasSocketAddress()) {
1✔
339
        return StructOrError.fromError(
×
340
            "Cluster " + clusterName
341
                + ": LOGICAL_DNS clusters must have an endpoint with address and socket_address");
342
      }
343
      SocketAddress socketAddress = lbEndpoint.getEndpoint().getAddress().getSocketAddress();
1✔
344
      if (!socketAddress.getResolverName().isEmpty()) {
1✔
345
        return StructOrError.fromError(
×
346
            "Cluster " + clusterName
347
                + ": LOGICAL DNS clusters must NOT have a custom resolver name set");
348
      }
349
      if (socketAddress.getPortSpecifierCase() != SocketAddress.PortSpecifierCase.PORT_VALUE) {
1✔
350
        return StructOrError.fromError(
×
351
            "Cluster " + clusterName
352
                + ": LOGICAL DNS clusters socket_address must have port_value");
353
      }
354
      String dnsHostName = String.format(
1✔
355
          Locale.US, "%s:%d", socketAddress.getAddress(), socketAddress.getPortValue());
1✔
356
      return StructOrError.fromStruct(CdsUpdate.forLogicalDns(
1✔
357
          clusterName, dnsHostName, lrsServerInfo, maxConcurrentRequests,
358
          upstreamTlsContext, isHttp11ProxyAvailable));
359
    }
360
    return StructOrError.fromError(
×
361
        "Cluster " + clusterName + ": unsupported built-in discovery type: " + type);
362
  }
363

364
  static io.envoyproxy.envoy.config.cluster.v3.OutlierDetection validateOutlierDetection(
365
      io.envoyproxy.envoy.config.cluster.v3.OutlierDetection outlierDetection)
366
      throws ResourceInvalidException {
367
    if (outlierDetection.hasInterval()) {
1✔
368
      if (!Durations.isValid(outlierDetection.getInterval())) {
1✔
369
        throw new ResourceInvalidException("outlier_detection interval is not a valid Duration");
1✔
370
      }
371
      if (hasNegativeValues(outlierDetection.getInterval())) {
1✔
372
        throw new ResourceInvalidException("outlier_detection interval has a negative value");
1✔
373
      }
374
    }
375
    if (outlierDetection.hasBaseEjectionTime()) {
1✔
376
      if (!Durations.isValid(outlierDetection.getBaseEjectionTime())) {
1✔
377
        throw new ResourceInvalidException(
1✔
378
            "outlier_detection base_ejection_time is not a valid Duration");
379
      }
380
      if (hasNegativeValues(outlierDetection.getBaseEjectionTime())) {
1✔
381
        throw new ResourceInvalidException(
1✔
382
            "outlier_detection base_ejection_time has a negative value");
383
      }
384
    }
385
    if (outlierDetection.hasMaxEjectionTime()) {
1✔
386
      if (!Durations.isValid(outlierDetection.getMaxEjectionTime())) {
1✔
387
        throw new ResourceInvalidException(
1✔
388
            "outlier_detection max_ejection_time is not a valid Duration");
389
      }
390
      if (hasNegativeValues(outlierDetection.getMaxEjectionTime())) {
1✔
391
        throw new ResourceInvalidException(
1✔
392
            "outlier_detection max_ejection_time has a negative value");
393
      }
394
    }
395
    if (outlierDetection.hasMaxEjectionPercent()
1✔
396
        && outlierDetection.getMaxEjectionPercent().getValue() > 100) {
1✔
397
      throw new ResourceInvalidException(
1✔
398
          "outlier_detection max_ejection_percent is > 100");
399
    }
400
    if (outlierDetection.hasEnforcingSuccessRate()
1✔
401
        && outlierDetection.getEnforcingSuccessRate().getValue() > 100) {
1✔
402
      throw new ResourceInvalidException(
1✔
403
          "outlier_detection enforcing_success_rate is > 100");
404
    }
405
    if (outlierDetection.hasFailurePercentageThreshold()
1✔
406
        && outlierDetection.getFailurePercentageThreshold().getValue() > 100) {
1✔
407
      throw new ResourceInvalidException(
1✔
408
          "outlier_detection failure_percentage_threshold is > 100");
409
    }
410
    if (outlierDetection.hasEnforcingFailurePercentage()
1✔
411
        && outlierDetection.getEnforcingFailurePercentage().getValue() > 100) {
1✔
412
      throw new ResourceInvalidException(
1✔
413
          "outlier_detection enforcing_failure_percentage is > 100");
414
    }
415

416
    return outlierDetection;
1✔
417
  }
418

419
  static boolean hasNegativeValues(Duration duration) {
420
    return duration.getSeconds() < 0 || duration.getNanos() < 0;
1✔
421
  }
422

423
  @VisibleForTesting
424
  static io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
425
      validateUpstreamTlsContext(
426
      io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext upstreamTlsContext,
427
      Set<String> certProviderInstances)
428
      throws ResourceInvalidException {
429
    if (upstreamTlsContext.hasCommonTlsContext()) {
1✔
430
      validateCommonTlsContext(upstreamTlsContext.getCommonTlsContext(), certProviderInstances,
1✔
431
          false);
432
    } else {
433
      throw new ResourceInvalidException("common-tls-context is required in upstream-tls-context");
1✔
434
    }
435
    return upstreamTlsContext;
1✔
436
  }
437

438
  @VisibleForTesting
439
  static void validateCommonTlsContext(
440
      CommonTlsContext commonTlsContext, Set<String> certProviderInstances, boolean server)
441
      throws ResourceInvalidException {
442
    if (commonTlsContext.hasCustomHandshaker()) {
1✔
443
      throw new ResourceInvalidException(
1✔
444
          "common-tls-context with custom_handshaker is not supported");
445
    }
446
    if (commonTlsContext.hasTlsParams()) {
1✔
447
      throw new ResourceInvalidException("common-tls-context with tls_params is not supported");
1✔
448
    }
449
    if (commonTlsContext.hasValidationContextSdsSecretConfig()) {
1✔
450
      throw new ResourceInvalidException(
1✔
451
          "common-tls-context with validation_context_sds_secret_config is not supported");
452
    }
453
    String certInstanceName = getIdentityCertInstanceName(commonTlsContext);
1✔
454
    if (certInstanceName == null) {
1✔
455
      if (server) {
1✔
456
        throw new ResourceInvalidException(
1✔
457
            "tls_certificate_provider_instance is required in downstream-tls-context");
458
      }
459
      if (commonTlsContext.getTlsCertificatesCount() > 0) {
1✔
460
        throw new ResourceInvalidException(
1✔
461
            "tls_certificate_provider_instance is unset");
462
      }
463
      if (commonTlsContext.getTlsCertificateSdsSecretConfigsCount() > 0) {
1✔
464
        throw new ResourceInvalidException(
1✔
465
            "tls_certificate_provider_instance is unset");
466
      }
467
    } else if (certProviderInstances == null || !certProviderInstances.contains(certInstanceName)) {
1✔
468
      throw new ResourceInvalidException(
1✔
469
          "CertificateProvider instance name '" + certInstanceName
470
              + "' not defined in the bootstrap file.");
471
    }
472
    String rootCaInstanceName = getRootCertInstanceName(commonTlsContext);
1✔
473
    if (rootCaInstanceName == null) {
1✔
474
      if (!server && (!enableSystemRootCerts
1✔
475
          || !CommonTlsContextUtil.isUsingSystemRootCerts(commonTlsContext))) {
1✔
476
        throw new ResourceInvalidException(
1✔
477
            "ca_certificate_provider_instance or system_root_certs is required in "
478
                + "upstream-tls-context");
479
      }
480
    } else {
481
      if (certProviderInstances == null || !certProviderInstances.contains(rootCaInstanceName)) {
1✔
482
        throw new ResourceInvalidException(
1✔
483
            "ca_certificate_provider_instance name '" + rootCaInstanceName
484
                + "' not defined in the bootstrap file.");
485
      }
486
      CertificateValidationContext certificateValidationContext = null;
1✔
487
      if (commonTlsContext.hasValidationContext()) {
1✔
488
        certificateValidationContext = commonTlsContext.getValidationContext();
1✔
489
      } else if (commonTlsContext.hasCombinedValidationContext() && commonTlsContext
1✔
490
          .getCombinedValidationContext().hasDefaultValidationContext()) {
1✔
491
        certificateValidationContext = commonTlsContext.getCombinedValidationContext()
1✔
492
            .getDefaultValidationContext();
1✔
493
      }
494
      if (certificateValidationContext != null) {
1✔
495
        @SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
496
        int matchSubjectAltNamesCount = certificateValidationContext.getMatchSubjectAltNamesCount();
1✔
497
        if (matchSubjectAltNamesCount > 0 && server) {
1✔
498
          throw new ResourceInvalidException(
1✔
499
              "match_subject_alt_names only allowed in upstream_tls_context");
500
        }
501
        if (certificateValidationContext.getVerifyCertificateSpkiCount() > 0) {
1✔
502
          throw new ResourceInvalidException(
1✔
503
              "verify_certificate_spki in default_validation_context is not supported");
504
        }
505
        if (certificateValidationContext.getVerifyCertificateHashCount() > 0) {
1✔
506
          throw new ResourceInvalidException(
1✔
507
              "verify_certificate_hash in default_validation_context is not supported");
508
        }
509
        if (certificateValidationContext.hasRequireSignedCertificateTimestamp()) {
1✔
510
          throw new ResourceInvalidException(
1✔
511
              "require_signed_certificate_timestamp in default_validation_context is not "
512
                  + "supported");
513
        }
514
        if (certificateValidationContext.hasCrl()) {
1✔
515
          throw new ResourceInvalidException("crl in default_validation_context is not supported");
1✔
516
        }
517
        if (certificateValidationContext.hasCustomValidatorConfig()) {
1✔
518
          throw new ResourceInvalidException(
1✔
519
              "custom_validator_config in default_validation_context is not supported");
520
        }
521
      }
522
    }
523
  }
1✔
524

525
  private static String getIdentityCertInstanceName(CommonTlsContext commonTlsContext) {
526
    if (commonTlsContext.hasTlsCertificateProviderInstance()) {
1✔
527
      return commonTlsContext.getTlsCertificateProviderInstance().getInstanceName();
1✔
528
    }
529
    return null;
1✔
530
  }
531

532
  private static String getRootCertInstanceName(CommonTlsContext commonTlsContext) {
533
    if (commonTlsContext.hasValidationContext()) {
1✔
534
      if (commonTlsContext.getValidationContext().hasCaCertificateProviderInstance()) {
1✔
535
        return commonTlsContext.getValidationContext().getCaCertificateProviderInstance()
1✔
536
            .getInstanceName();
1✔
537
      }
538
    } else if (commonTlsContext.hasCombinedValidationContext()) {
1✔
539
      CommonTlsContext.CombinedCertificateValidationContext combinedCertificateValidationContext
1✔
540
          = commonTlsContext.getCombinedValidationContext();
1✔
541
      if (combinedCertificateValidationContext.hasDefaultValidationContext()
1✔
542
          && combinedCertificateValidationContext.getDefaultValidationContext()
1✔
543
          .hasCaCertificateProviderInstance()) {
1✔
544
        return combinedCertificateValidationContext.getDefaultValidationContext()
1✔
545
            .getCaCertificateProviderInstance().getInstanceName();
1✔
546
      }
547
    }
548
    return null;
1✔
549
  }
550

551
  /** xDS resource update for cluster-level configuration. */
552
  @AutoValue
553
  abstract static class CdsUpdate implements ResourceUpdate {
1✔
554
    abstract String clusterName();
555

556
    abstract ClusterType clusterType();
557

558
    abstract ImmutableMap<String, ?> lbPolicyConfig();
559

560
    // Only valid if lbPolicy is "ring_hash_experimental".
561
    abstract long minRingSize();
562

563
    // Only valid if lbPolicy is "ring_hash_experimental".
564
    abstract long maxRingSize();
565

566
    // Only valid if lbPolicy is "least_request_experimental".
567
    abstract int choiceCount();
568

569
    // Alternative resource name to be used in EDS requests.
570
    /// Only valid for EDS cluster.
571
    @Nullable
572
    abstract String edsServiceName();
573

574
    // Corresponding DNS name to be used if upstream endpoints of the cluster is resolvable
575
    // via DNS.
576
    // Only valid for LOGICAL_DNS cluster.
577
    @Nullable
578
    abstract String dnsHostName();
579

580
    // Load report server info for reporting loads via LRS.
581
    // Only valid for EDS or LOGICAL_DNS cluster.
582
    @Nullable
583
    abstract ServerInfo lrsServerInfo();
584

585
    // Max number of concurrent requests can be sent to this cluster.
586
    // Only valid for EDS or LOGICAL_DNS cluster.
587
    @Nullable
588
    abstract Long maxConcurrentRequests();
589

590
    // TLS context used to connect to connect to this cluster.
591
    // Only valid for EDS or LOGICAL_DNS cluster.
592
    @Nullable
593
    abstract UpstreamTlsContext upstreamTlsContext();
594

595
    abstract boolean isHttp11ProxyAvailable();
596

597
    // List of underlying clusters making of this aggregate cluster.
598
    // Only valid for AGGREGATE cluster.
599
    @Nullable
600
    abstract ImmutableList<String> prioritizedClusterNames();
601

602
    // Outlier detection configuration.
603
    @Nullable
604
    abstract OutlierDetection outlierDetection();
605

606
    abstract ImmutableMap<String, Struct> filterMetadata();
607

608
    abstract ImmutableMap<String, Object> parsedMetadata();
609

610
    private static Builder newBuilder(String clusterName) {
611
      return new AutoValue_XdsClusterResource_CdsUpdate.Builder()
1✔
612
          .clusterName(clusterName)
1✔
613
          .minRingSize(0)
1✔
614
          .maxRingSize(0)
1✔
615
          .choiceCount(0)
1✔
616
          .filterMetadata(ImmutableMap.of())
1✔
617
          .parsedMetadata(ImmutableMap.of())
1✔
618
          .isHttp11ProxyAvailable(false);
1✔
619
    }
620

621
    static Builder forAggregate(String clusterName, List<String> prioritizedClusterNames) {
622
      checkNotNull(prioritizedClusterNames, "prioritizedClusterNames");
1✔
623
      return newBuilder(clusterName)
1✔
624
          .clusterType(ClusterType.AGGREGATE)
1✔
625
          .prioritizedClusterNames(ImmutableList.copyOf(prioritizedClusterNames));
1✔
626
    }
627

628
    static Builder forEds(String clusterName, @Nullable String edsServiceName,
629
                          @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
630
                          @Nullable UpstreamTlsContext upstreamTlsContext,
631
                          @Nullable OutlierDetection outlierDetection,
632
                          boolean isHttp11ProxyAvailable) {
633
      return newBuilder(clusterName)
1✔
634
          .clusterType(ClusterType.EDS)
1✔
635
          .edsServiceName(edsServiceName)
1✔
636
          .lrsServerInfo(lrsServerInfo)
1✔
637
          .maxConcurrentRequests(maxConcurrentRequests)
1✔
638
          .upstreamTlsContext(upstreamTlsContext)
1✔
639
          .outlierDetection(outlierDetection)
1✔
640
          .isHttp11ProxyAvailable(isHttp11ProxyAvailable);
1✔
641
    }
642

643
    static Builder forLogicalDns(String clusterName, String dnsHostName,
644
                                 @Nullable ServerInfo lrsServerInfo,
645
                                 @Nullable Long maxConcurrentRequests,
646
                                 @Nullable UpstreamTlsContext upstreamTlsContext,
647
                                 boolean isHttp11ProxyAvailable) {
648
      return newBuilder(clusterName)
1✔
649
          .clusterType(ClusterType.LOGICAL_DNS)
1✔
650
          .dnsHostName(dnsHostName)
1✔
651
          .lrsServerInfo(lrsServerInfo)
1✔
652
          .maxConcurrentRequests(maxConcurrentRequests)
1✔
653
          .upstreamTlsContext(upstreamTlsContext)
1✔
654
          .isHttp11ProxyAvailable(isHttp11ProxyAvailable);
1✔
655
    }
656

657
    enum ClusterType {
1✔
658
      EDS, LOGICAL_DNS, AGGREGATE
1✔
659
    }
660

661
    enum LbPolicy {
×
662
      ROUND_ROBIN, RING_HASH, LEAST_REQUEST
×
663
    }
664

665
    // FIXME(chengyuanzhang): delete this after UpstreamTlsContext's toString() is fixed.
666
    @Override
667
    public final String toString() {
668
      return MoreObjects.toStringHelper(this)
1✔
669
          .add("clusterName", clusterName())
1✔
670
          .add("clusterType", clusterType())
1✔
671
          .add("lbPolicyConfig", lbPolicyConfig())
1✔
672
          .add("minRingSize", minRingSize())
1✔
673
          .add("maxRingSize", maxRingSize())
1✔
674
          .add("choiceCount", choiceCount())
1✔
675
          .add("edsServiceName", edsServiceName())
1✔
676
          .add("dnsHostName", dnsHostName())
1✔
677
          .add("lrsServerInfo", lrsServerInfo())
1✔
678
          .add("maxConcurrentRequests", maxConcurrentRequests())
1✔
679
          // Exclude upstreamTlsContext and outlierDetection as their string representations are
680
          // cumbersome.
681
          .add("prioritizedClusterNames", prioritizedClusterNames())
1✔
682
          .toString();
1✔
683
    }
684

685
    @AutoValue.Builder
686
    abstract static class Builder {
1✔
687
      // Private, use one of the static factory methods instead.
688
      protected abstract Builder clusterName(String clusterName);
689

690
      // Private, use one of the static factory methods instead.
691
      protected abstract Builder clusterType(ClusterType clusterType);
692

693
      protected abstract Builder lbPolicyConfig(ImmutableMap<String, ?> lbPolicyConfig);
694

695
      Builder roundRobinLbPolicy() {
696
        return this.lbPolicyConfig(ImmutableMap.of("round_robin", ImmutableMap.of()));
1✔
697
      }
698

699
      Builder ringHashLbPolicy(Long minRingSize, Long maxRingSize) {
700
        return this.lbPolicyConfig(ImmutableMap.of("ring_hash_experimental",
1✔
701
            ImmutableMap.of("minRingSize", minRingSize.doubleValue(), "maxRingSize",
1✔
702
                maxRingSize.doubleValue())));
1✔
703
      }
704

705
      Builder leastRequestLbPolicy(Integer choiceCount) {
706
        return this.lbPolicyConfig(ImmutableMap.of("least_request_experimental",
1✔
707
            ImmutableMap.of("choiceCount", choiceCount.doubleValue())));
1✔
708
      }
709

710
      // Private, use leastRequestLbPolicy(int).
711
      protected abstract Builder choiceCount(int choiceCount);
712

713
      // Private, use ringHashLbPolicy(long, long).
714
      protected abstract Builder minRingSize(long minRingSize);
715

716
      // Private, use ringHashLbPolicy(long, long).
717
      protected abstract Builder maxRingSize(long maxRingSize);
718

719
      // Private, use CdsUpdate.forEds() instead.
720
      protected abstract Builder edsServiceName(String edsServiceName);
721

722
      // Private, use CdsUpdate.forLogicalDns() instead.
723
      protected abstract Builder dnsHostName(String dnsHostName);
724

725
      // Private, use one of the static factory methods instead.
726
      protected abstract Builder lrsServerInfo(ServerInfo lrsServerInfo);
727

728
      // Private, use one of the static factory methods instead.
729
      protected abstract Builder maxConcurrentRequests(Long maxConcurrentRequests);
730

731
      protected abstract Builder isHttp11ProxyAvailable(boolean isHttp11ProxyAvailable);
732

733
      // Private, use one of the static factory methods instead.
734
      protected abstract Builder upstreamTlsContext(UpstreamTlsContext upstreamTlsContext);
735

736
      // Private, use CdsUpdate.forAggregate() instead.
737
      protected abstract Builder prioritizedClusterNames(List<String> prioritizedClusterNames);
738

739
      protected abstract Builder outlierDetection(OutlierDetection outlierDetection);
740

741
      protected abstract Builder filterMetadata(ImmutableMap<String, Struct> filterMetadata);
742

743
      protected abstract Builder parsedMetadata(ImmutableMap<String, Object> parsedMetadata);
744

745
      abstract CdsUpdate build();
746
    }
747
  }
748
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc