From ff1a799364266a8ba79b33316729f093a2d8d4d7 Mon Sep 17 00:00:00 2001 From: whowes Date: Mon, 30 Nov 2026 22:04:59 +0000 Subject: [PATCH] fix(core): resolve universe domain and track explicit host in ServiceOptions --- .../java/com/google/cloud/ServiceOptions.java | 100 ++++-- .../com/google/cloud/ServiceOptionsTest.java | 338 +++++++++++++++++- 2 files changed, 406 insertions(+), 32 deletions(-) diff --git a/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index 9935e384206b..508f201e3459 100644 --- a/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -37,6 +37,7 @@ import com.google.api.core.InternalApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.EndpointContext; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.NoHeaderProvider; @@ -49,6 +50,7 @@ import com.google.auth.oauth2.QuotaProjectIdProvider; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.spi.ServiceRpcFactory; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -102,6 +104,7 @@ public abstract class ServiceOptions< private final String projectId; private final String universeDomain; private final String host; + private volatile Boolean hasExplicitHost; private final RetrySettings retrySettings; private final String serviceRpcFactoryClassName; private final String serviceFactoryClassName; @@ -156,7 +159,10 @@ protected Builder() {} protected Builder(ServiceOptions options) { projectId = options.projectId; universeDomain = options.universeDomain; - host = options.host; + // Copy only an explicit host so toBuilder().setUniverseDomain(...) recomputes defaults. + if (options.hasExplicitHost()) { + host = options.host; + } credentials = options.credentials; retrySettings = options.retrySettings; serviceFactory = options.serviceFactory; @@ -221,10 +227,10 @@ public B setHost(String host) { * Universe Domain value of `googleapis.com` and cloudasset.test.com would have a Universe * Domain of `test.com`. * - *

If this value is not set, the resolved UniverseDomain will default to `googleapis.com`. + *

If this value is not set, the {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN} environment variable is + * used if set, otherwise the resolved UniverseDomain defaults to `googleapis.com`. * - * @throws NullPointerException if {@code universeDomain} is {@code null}. The resolved - * universeDomain will be `googleapis.com` if this value is not set. + * @throws NullPointerException if {@code universeDomain} is {@code null}. */ public B setUniverseDomain(String universeDomain) { this.universeDomain = checkNotNull(universeDomain); @@ -362,7 +368,12 @@ protected ServiceOptions( + "or the environment. Please set a project ID using the builder."); } universeDomain = builder.universeDomain; - host = firstNonNull(builder.host, getDefaultHost()); + hasExplicitHost = builder.host != null; + if (builder.host != null) { + host = builder.host; + } else { + host = getDefaultHost(); + } credentials = builder.credentials != null ? builder.credentials : defaultCredentials(); retrySettings = firstNonNull(builder.retrySettings, getDefaultRetrySettings()); serviceFactory = @@ -658,6 +669,15 @@ public String getHost() { return host; } + /** + * Returns whether a host was explicitly configured via {@link Builder#setHost(String)} rather + * than defaulted by {@link #getDefaultHost()}. + */ + @InternalApi + public boolean hasExplicitHost() { + return Boolean.TRUE.equals(hasExplicitHost); + } + /** Returns the authentication credentials. */ public Credentials getCredentials() { return credentials; @@ -789,6 +809,9 @@ private void readObject(ObjectInputStream input) throws IOException, ClassNotFou input.defaultReadObject(); serviceFactory = newInstance(serviceFactoryClassName, ServiceFactory.class); serviceRpcFactory = newInstance(serviceRpcFactoryClassName, ServiceRpcFactory.class); + if (hasExplicitHost == null) { + hasExplicitHost = !Objects.equals(host, getDefaultHost()); + } } /** @@ -898,28 +921,52 @@ public boolean getUseJwtAccessWithScope() { return useJwtAccessWithScope; } + /** + * Returns the resolved universe domain using the precedence: + * + *

    + *
  1. Explicitly configured {@link #getUniverseDomain()} + *
  2. {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN} environment variable + *
  3. Default {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}) + *
+ * + * @throws IllegalArgumentException if the resolved universe domain is empty + */ + @InternalApi + public String resolveUniverseDomain() { + String resolved = universeDomain; + if (resolved == null) { + resolved = getUniverseDomainFromEnv(); + } + if (resolved == null) { + return Credentials.GOOGLE_DEFAULT_UNIVERSE; + } + if (resolved.isEmpty()) { + throw new IllegalArgumentException("The universe domain cannot be empty"); + } + return resolved; + } + + @VisibleForTesting + String getUniverseDomainFromEnv() { + return System.getenv(EndpointContext.GOOGLE_CLOUD_UNIVERSE_DOMAIN); + } + /** * Returns the resolved host for the Service to connect to Google Cloud * - *

The resolved host will be in `https://{serviceName}.{resolvedUniverseDomain}` format. The - * resolvedUniverseDomain will be set to `googleapis.com` if universeDomain is null. The format is - * similar to the DEFAULT_HOST value in java-core. + *

The resolved host will be in `https://{serviceName}.{resolvedUniverseDomain}` format, where + * {@code resolvedUniverseDomain} is determined by {@link #resolveUniverseDomain()}. If the user + * explicitly configured a host other than {@code DEFAULT_HOST} via {@link + * Builder#setHost(String)}, that host is returned as-is. * * @see DEFAULT_HOST */ @InternalApi public String getResolvedHost(String serviceName) { - if (universeDomain != null && universeDomain.isEmpty()) { - throw new IllegalArgumentException("The universe domain cannot be empty"); - } - String resolvedUniverseDomain = - universeDomain != null ? universeDomain : Credentials.GOOGLE_DEFAULT_UNIVERSE; - // The host value set to DEFAULT_HOST if the user didn't configure a host. If the - // user set a host the library uses that value, otherwise, construct the host for the user. - // The DEFAULT_HOST value is not a valid host for handwritten libraries and should be - // overriden to include the serviceName. - if (!DEFAULT_HOST.equals(host)) { + String resolvedUniverseDomain = resolveUniverseDomain(); + if (hasExplicitHost() && !DEFAULT_HOST.equals(host)) { return host; } return "https://" + serviceName + "." + resolvedUniverseDomain; @@ -930,22 +977,20 @@ public String getResolvedHost(String serviceName) { * removed in the future when Apiary clients can resolve their endpoints. Returns the host to be * used as the rootUrl. * - *

The resolved host will be in `https://{serviceName}.{resolvedUniverseDomain}/` format. The - * resolvedUniverseDomain will be set to `googleapis.com` if universeDomain is null. - * - *

The host value is set to DEFAULT_HOST if the user didn't configure a host. Returns the host - * value the user set, otherwise constructs the host for the user. + *

The resolved host will be in `https://{serviceName}.{resolvedUniverseDomain}/` format, where + * {@code resolvedUniverseDomain} is determined by {@link #resolveUniverseDomain()}. If the user + * explicitly configured a host other than {@code DEFAULT_HOST} via {@link + * Builder#setHost(String)}, that host is returned as-is. * * @see rootUrl */ @InternalApi public String getResolvedApiaryHost(String serviceName) { - if (!DEFAULT_HOST.equals(host)) { + String resolvedUniverseDomain = resolveUniverseDomain(); + if (hasExplicitHost() && !DEFAULT_HOST.equals(host)) { return host; } - String resolvedUniverseDomain = - universeDomain != null ? universeDomain : Credentials.GOOGLE_DEFAULT_UNIVERSE; return "https://" + serviceName + "." + resolvedUniverseDomain + "/"; } @@ -959,14 +1004,13 @@ public String getResolvedApiaryHost(String serviceName) { */ @InternalApi public boolean hasValidUniverseDomain() throws IOException { + String resolvedUniverseDomain = resolveUniverseDomain(); Credentials credentials = getCredentials(); // API keys carry no universe domain metadata. Callers are responsible for ensuring the API key // belongs to the configured universe domain. if (credentials instanceof ApiKeyCredentials) { return true; } - String resolvedUniverseDomain = - universeDomain != null ? universeDomain : Credentials.GOOGLE_DEFAULT_UNIVERSE; // Fall back to GDU when credentials are null to match EndpointContext and HttpTransportOptions. String credentialsUniverseDomain = credentials != null ? credentials.getUniverseDomain() : Credentials.GOOGLE_DEFAULT_UNIVERSE; diff --git a/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index e5e6ff3dfb7f..203b0101fd51 100644 --- a/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -52,6 +52,7 @@ import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Set; @@ -313,12 +314,23 @@ private static class DefaultTestServiceRpc implements TestServiceRpc { } static class TestServiceOptions extends ServiceOptions { - private static class Builder - extends ServiceOptions.Builder { - private Builder() {} + private static final long serialVersionUID = 1L; + + private final String envUniverseDomain; + + static class Builder extends ServiceOptions.Builder { + private String envUniverseDomain; - private Builder(TestServiceOptions options) { + Builder() {} + + Builder(TestServiceOptions options) { super(options); + this.envUniverseDomain = options.envUniverseDomain; + } + + Builder setEnvUniverseDomain(String envUniverseDomain) { + this.envUniverseDomain = envUniverseDomain; + return this; } @Override @@ -333,6 +345,12 @@ protected TestServiceOptions build() { TestServiceRpcFactory.class, builder, new TestServiceDefaults()); + this.envUniverseDomain = builder.envUniverseDomain; + } + + @Override + String getUniverseDomainFromEnv() { + return envUniverseDomain; } private static class TestServiceDefaults @@ -379,6 +397,77 @@ public int hashCode() { } } + static class DynamicHostTestServiceOptions extends TestServiceOptions { + private static final long serialVersionUID = 1L; + + private static class Builder extends TestServiceOptions.Builder { + private Builder() {} + + private Builder(DynamicHostTestServiceOptions options) { + super(options); + } + + @Override + protected DynamicHostTestServiceOptions build() { + return new DynamicHostTestServiceOptions(this); + } + } + + private DynamicHostTestServiceOptions(Builder builder) { + super(builder); + } + + @Override + protected String getDefaultHost() { + return getResolvedHost("dynamic"); + } + + @Override + public Builder toBuilder() { + return new Builder(this); + } + + private static Builder newBuilder() { + return new Builder(); + } + } + + static class StaticDefaultHostTestServiceOptions extends TestServiceOptions { + private static final long serialVersionUID = 1L; + private static final String SERVICE_DEFAULT_HOST = "https://static-service.googleapis.com"; + + private static class Builder extends TestServiceOptions.Builder { + private Builder() {} + + private Builder(StaticDefaultHostTestServiceOptions options) { + super(options); + } + + @Override + protected StaticDefaultHostTestServiceOptions build() { + return new StaticDefaultHostTestServiceOptions(this); + } + } + + private StaticDefaultHostTestServiceOptions(Builder builder) { + super(builder); + } + + @Override + protected String getDefaultHost() { + return SERVICE_DEFAULT_HOST; + } + + @Override + public Builder toBuilder() { + return new Builder(this); + } + + private static Builder newBuilder() { + return new Builder(); + } + } + @Test public void testBuilder() { assertSame(credentials, OPTIONS.getCredentials()); @@ -723,6 +812,247 @@ public com.google.auth.Credentials getCredentials() { assertThat(customOptions.hasValidUniverseDomain()).isFalse(); } + @Test + void testResolveUniverseDomain_unset_defaultsToGoogleDefaultUniverse() { + TestServiceOptions options = TestServiceOptions.newBuilder().setProjectId("project-id").build(); + + assertThat(options.resolveUniverseDomain()).isEqualTo("googleapis.com"); + } + + @Test + void testResolveUniverseDomain_envVarSet_returnsEnvVar() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setEnvUniverseDomain("env.example.com") + .build(); + + assertThat(options.resolveUniverseDomain()).isEqualTo("env.example.com"); + } + + @Test + void testResolveUniverseDomain_explicitAndEnvVarSet_prefersExplicit() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setUniverseDomain("explicit.example.com") + .setEnvUniverseDomain("env.example.com") + .build(); + + assertThat(options.resolveUniverseDomain()).isEqualTo("explicit.example.com"); + } + + @Test + void testResolveUniverseDomain_emptyExplicitWithEnvVar_throwsIllegalArgumentException() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setUniverseDomain("") + .setEnvUniverseDomain("env.example.com") + .build(); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, options::resolveUniverseDomain); + assertThat(exception.getMessage()).isEqualTo("The universe domain cannot be empty"); + } + + @Test + void testResolveUniverseDomain_emptyEnvVar_throwsIllegalArgumentException() { + TestServiceOptions options = + TestServiceOptions.newBuilder().setProjectId("project-id").setEnvUniverseDomain("").build(); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, options::resolveUniverseDomain); + assertThat(exception.getMessage()).isEqualTo("The universe domain cannot be empty"); + } + + @Test + void testGetResolvedHost_usesEnvVar() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setEnvUniverseDomain("env.example.com") + .build(); + + assertThat(options.getResolvedHost("service")).isEqualTo("https://service.env.example.com"); + } + + @Test + void testGetResolvedApiaryHost_usesEnvVar() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setEnvUniverseDomain("env.example.com") + .build(); + + assertThat(options.getResolvedApiaryHost("service")) + .isEqualTo("https://service.env.example.com/"); + } + + @Test + void testGetResolvedHost_staticSubclassDefaultHost_resolvesFromUniverseDomain() { + TestServiceOptions options = + StaticDefaultHostTestServiceOptions.newBuilder() + .setProjectId("project-id") + .setEnvUniverseDomain("env.example.com") + .build(); + + assertThat(options.hasExplicitHost()).isFalse(); + assertThat(options.getResolvedHost("static-service")) + .isEqualTo("https://static-service.env.example.com"); + } + + @Test + void testGetResolvedHost_explicitDefaultHost_resolvesFromUniverseDomain() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://www.googleapis.com") + .setUniverseDomain("custom.example.com") + .build(); + + assertThat(options.hasExplicitHost()).isTrue(); + assertThat(options.getResolvedHost("service")).isEqualTo("https://service.custom.example.com"); + } + + @Test + void testGetResolvedApiaryHost_emptyEnvVarWithExplicitHost_throwsIllegalArgumentException() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://custom.example.com/") + .setEnvUniverseDomain("") + .build(); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> options.getResolvedApiaryHost("service")); + assertThat(exception.getMessage()).isEqualTo("The universe domain cannot be empty"); + } + + @Test + void testHasValidUniverseDomain_envVarMatchesCredentials_returnsTrue() throws IOException { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setEnvUniverseDomain("random.com") + .setCredentials(credentialsNotInGDU) + .build(); + + assertThat(options.hasValidUniverseDomain()).isTrue(); + } + + @Test + void testHasValidUniverseDomain_envVarMismatchesCredentials_returnsFalse() throws IOException { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setEnvUniverseDomain("random.com") + .setCredentials(credentials) + .build(); + + assertThat(options.hasValidUniverseDomain()).isFalse(); + } + + @Test + void testHasValidUniverseDomain_emptyUniverseDomainWithApiKey_throwsIllegalArgumentException() { + TestServiceOptions options = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setUniverseDomain("") + .setCredentials(ApiKeyCredentials.create("test-api-key")) + .build(); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, options::hasValidUniverseDomain); + assertThat(exception.getMessage()).isEqualTo("The universe domain cannot be empty"); + } + + @Test + void testToBuilder_defaultHost_recomputesHostForNewUniverseDomain() { + TestServiceOptions original = + DynamicHostTestServiceOptions.newBuilder().setProjectId("project-id").build(); + + TestServiceOptions rebuilt = + original.toBuilder().setUniverseDomain("custom.example.com").build(); + + assertThat(rebuilt.hasExplicitHost()).isFalse(); + assertThat(rebuilt.getHost()).isEqualTo("https://dynamic.custom.example.com"); + } + + @Test + void testToBuilder_explicitHost_preservesHostForNewUniverseDomain() { + TestServiceOptions original = + DynamicHostTestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://override.example.com") + .build(); + + TestServiceOptions rebuilt = + original.toBuilder().setUniverseDomain("custom.example.com").build(); + + assertThat(rebuilt.hasExplicitHost()).isTrue(); + assertThat(rebuilt.getHost()).isEqualTo("https://override.example.com"); + } + + @Test + void testSerialization_legacyStreamDefaultHost_infersNonExplicitHost() throws Exception { + TestServiceOptions original = + DynamicHostTestServiceOptions.newBuilder() + .setProjectId("project-id") + .setCredentials(NoCredentials.getInstance()) + .setServiceFactory(new PublicTestServiceFactory()) + .setServiceRpcFactory(new PublicTestServiceRpcFactory()) + .setTransportOptions(new SerializableTransportOptions()) + .build(); + + TestServiceOptions deserialized = roundTripLegacySerialize(original); + + assertThat(deserialized.hasExplicitHost()).isFalse(); + assertThat(deserialized.toBuilder().setUniverseDomain("custom.example.com").build().getHost()) + .isEqualTo("https://dynamic.custom.example.com"); + } + + @Test + void testSerialization_legacyStreamExplicitHost_infersExplicitHost() throws Exception { + TestServiceOptions original = + DynamicHostTestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://override.example.com") + .setCredentials(NoCredentials.getInstance()) + .setServiceFactory(new PublicTestServiceFactory()) + .setServiceRpcFactory(new PublicTestServiceRpcFactory()) + .setTransportOptions(new SerializableTransportOptions()) + .build(); + + TestServiceOptions deserialized = roundTripLegacySerialize(original); + + assertThat(deserialized.hasExplicitHost()).isTrue(); + assertThat(deserialized.toBuilder().setUniverseDomain("custom.example.com").build().getHost()) + .isEqualTo("https://override.example.com"); + } + + private static TestServiceOptions roundTripLegacySerialize(TestServiceOptions options) + throws Exception { + // Simulate streams serialized before hasExplicitHost existed (deserialized as null). + Field hasExplicitHostField = ServiceOptions.class.getDeclaredField("hasExplicitHost"); + hasExplicitHostField.setAccessible(true); + hasExplicitHostField.set(options, null); + return roundTripSerialize(options); + } + + @SuppressWarnings("unchecked") + private static T roundTripSerialize(T object) throws IOException, ClassNotFoundException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(object); + } + try (ObjectInputStream ois = + new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + return (T) ois.readObject(); + } + } + @Test void testGetScopedCredentials_useJwtAccessWithScope_enablesByDefault() { TestServiceOptions options =