From e1231d2313050e2e841d9734ef45402766740a18 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 16:28:26 +0000 Subject: [PATCH 1/5] fix(bigquery-jdbc): add Clearcut diagnostic telemetry coordinator and driver integration --- .../cloud/bigquery/jdbc/BigQueryDriver.java | 21 +- .../jdbc/BigQueryJdbcDiagnosticTelemetry.java | 404 ++++++++++++++++ .../bigquery/jdbc/BigQueryJdbcBaseTest.java | 27 ++ .../BigQueryJdbcDiagnosticTelemetryTest.java | 445 ++++++++++++++++++ .../jdbc/BigQueryJdbcUrlUtilityTest.java | 37 ++ 5 files changed, 918 insertions(+), 16 deletions(-) create mode 100644 java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java create mode 100644 java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index 561cc75d918b..9e4a17d76374 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -130,25 +130,17 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException public Connection connect(String url, Properties info) throws SQLException { LOG.finest("++enter++"); AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + String connectionUri = null; + DataSource ds = null; try { if (acceptsURL(url)) { Properties connectInfo = info == null ? new Properties() : (Properties) info.clone(); Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry"); - String connectionUri = + connectionUri = BigQueryJdbcUrlUtility.appendPropertiesToURL( url.substring(5), this.toString(), connectInfo); - String telemetryOptOut = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); - - if (telemetryOptOut != null) { - connectInfo.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut); - } - TelemetryManager.getInstance(connectInfo); - Level logLevel; String logPath; boolean ignoredUrlLogPath; @@ -199,7 +191,6 @@ public Connection connect(String url, Properties info) throws SQLException { BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); } - DataSource ds; try { ds = DataSource.fromUrl(connectionUri); } catch (BigQueryJdbcRuntimeException e) { @@ -240,12 +231,10 @@ public Connection connect(String url, Properties info) throws SQLException { return null; } } catch (IOException e) { - TelemetryManager.recordConnectionAttempt( - Status.STATUS_ERROR, TelemetryManager.extractErrorCode(e), authType); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection(connectionUri, ds, authType, e); throw new BigQueryJdbcException("Failed to establish connection", e); } catch (Throwable t) { - TelemetryManager.recordConnectionAttempt( - Status.STATUS_ERROR, TelemetryManager.extractErrorCode(t), authType); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection(connectionUri, ds, authType, t); throw t; } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java new file mode 100644 index 000000000000..b07d20d1acdd --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java @@ -0,0 +1,404 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.bigquery.jdbc; + +import com.google.api.client.http.HttpTransport; +import com.google.auth.Credentials; +import com.google.auth.oauth2.ComputeEngineCredentials; +import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType; +import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.common.hash.Hasher; +import com.google.common.hash.Hashing; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.regex.Pattern; + +/** + * Coordinates Clearcut diagnostic telemetry eligibility, transport-profile isolation, and lifecycle + * transitions for BigQuery JDBC connections. + */ +final class BigQueryJdbcDiagnosticTelemetry { + private static final Pattern VALID_PORT_PATTERN = + Pattern.compile(BigQueryJdbcProxyUtility.validPortRegex); + + private BigQueryJdbcDiagnosticTelemetry() {} + + /** + * Initializes Clearcut diagnostic telemetry with the connection's proxy and SSL TrustStore + * settings, or permanently disables it if the connection opts out, targets a non-default universe + * or endpoint override, or conflicts with an active transport profile. + */ + static void initializeOrDisable( + DataSource ds, Map proxyProperties, Credentials credentials) { + if (TelemetryManager.isGloballyDisabled()) { + return; + } + TelemetryManager.runSafely( + () -> { + if (isSuppressed(ds, credentials)) { + TelemetryManager.disableGlobally(); + return; + } + initializeWithTransport( + buildEnableProperties(ds.getEnableDiagnosticTelemetry()), + proxyProperties, + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider()); + }); + } + + /** + * Enforces suppression and opt-out rules on failed {@link BigQueryDriver#connect} calls and + * records a failed connection attempt when diagnostic telemetry is eligible and transport + * configuration is valid. + */ + static void recordFailedConnection( + String connectionUri, DataSource ds, AuthenticationType authType, Throwable failure) { + if (connectionUri == null || TelemetryManager.isGloballyDisabled()) { + return; + } + TelemetryManager.runSafely( + () -> { + TelemetryManager manager = + ds != null + ? initializeOrDisableForFailedDataSource(ds) + : initializeOrDisableFromRawUri(connectionUri); + if (manager != null) { + TelemetryManager.recordConnectionAttempt( + Status.STATUS_ERROR, TelemetryManager.extractErrorCode(failure), authType); + } + }); + } + + private static TelemetryManager initializeOrDisableForFailedDataSource(DataSource ds) { + if (isSuppressed(ds, null)) { + TelemetryManager.disableGlobally(); + return null; + } + Properties enableProps = buildEnableProperties(ds.getEnableDiagnosticTelemetry()); + if (!TelemetryManager.isConfigEnabled(enableProps)) { + TelemetryManager.disableGlobally(); + return null; + } + Optional> parsedProxy = tryParseProxyPropertiesSilently(ds); + if (!parsedProxy.isPresent()) { + return null; + } + return initializeWithTransport( + enableProps, + parsedProxy.get(), + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider()); + } + + private static TelemetryManager initializeOrDisableFromRawUri(String connectionUri) { + if (isSuppressedFromRawUri(connectionUri)) { + TelemetryManager.disableGlobally(); + return null; + } + Properties enableProps = new Properties(); + try { + String rawEnable = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + if (rawEnable != null && !rawEnable.isEmpty()) { + enableProps.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, rawEnable); + } + } catch (RuntimeException e) { + TelemetryManager.disableGlobally(); + return null; + } + if (!TelemetryManager.isConfigEnabled(enableProps)) { + TelemetryManager.disableGlobally(); + return null; + } + Optional> parsedProxy = tryParseProxyPropertiesFromRawUri(connectionUri); + if (!parsedProxy.isPresent()) { + return null; + } + Optional parsedSsl = tryParseTrustStoreFromRawUri(connectionUri); + if (!parsedSsl.isPresent()) { + return null; + } + TrustStoreSettings ssl = parsedSsl.get(); + return initializeWithTransport( + enableProps, parsedProxy.get(), ssl.path, ssl.password, ssl.type, ssl.provider); + } + + private static TelemetryManager initializeWithTransport( + Properties enableProps, + Map proxyProperties, + String sslTrustStorePath, + String sslTrustStorePassword, + String sslTrustStoreType, + String sslTrustStoreProvider) { + String profileKey = + computeTransportProfileKey( + proxyProperties, + sslTrustStorePath, + sslTrustStorePassword, + sslTrustStoreType, + sslTrustStoreProvider); + return TelemetryManager.getInstance( + enableProps, + profileKey, + () -> + createClearcutHttpTransport( + proxyProperties, + sslTrustStorePath, + sslTrustStorePassword, + sslTrustStoreType, + sslTrustStoreProvider), + profileKey != null); + } + + static boolean isSuppressed(DataSource ds, Credentials credentials) { + if (isNonBlank(ds.getEndpointOverrides()) || isNonBlank(ds.getPrivateServiceConnect())) { + return true; + } + if (isNonDefaultUniverse(ds.resolveUniverseDomain())) { + return true; + } + return isNonDefaultCredentialUniverse(credentials); + } + + private static boolean isSuppressedFromRawUri(String connectionUri) { + try { + String endpointOverrides = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME); + if (isNonBlank(endpointOverrides)) { + return true; + } + String privateServiceConnect = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); + if (isNonBlank(privateServiceConnect)) { + return true; + } + String rawUniverse = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME); + String explicitUniverse = BigQueryJdbcUrlUtility.normalizeUniverseDomain(rawUniverse); + String resolvedUniverse = + explicitUniverse != null + ? explicitUniverse + : BigQueryJdbcUrlUtility.getEnvUniverseDomain(); + return isNonDefaultUniverse(resolvedUniverse); + } catch (RuntimeException e) { + return true; + } + } + + private static Properties buildEnableProperties(boolean enabled) { + Properties props = new Properties(); + props.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, String.valueOf(enabled)); + return props; + } + + /** + * Validates and extracts proxy properties without emitting duplicate {@code SEVERE} logs. Returns + * {@link Optional#empty()} when the proxy configuration is incomplete or malformed. + */ + static Optional> tryParseProxyPropertiesSilently(DataSource ds) { + return tryParseProxyPropertiesSilently( + ds.getProxyHost(), ds.getProxyPort(), ds.getProxyUid(), ds.getProxyPwd()); + } + + private static Optional> tryParseProxyPropertiesFromRawUri( + String connectionUri) { + try { + String proxyHost = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME); + String proxyPort = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME); + String proxyUid = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME); + String proxyPwd = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME); + return tryParseProxyPropertiesSilently(proxyHost, proxyPort, proxyUid, proxyPwd); + } catch (RuntimeException e) { + return Optional.empty(); + } + } + + private static Optional> tryParseProxyPropertiesSilently( + String proxyHost, String proxyPort, String proxyUid, String proxyPwd) { + if (proxyHost == null && proxyPort == null && proxyUid == null && proxyPwd == null) { + return Optional.of(Collections.emptyMap()); + } + if (proxyHost == null || proxyHost.trim().isEmpty() || proxyPort == null) { + return Optional.empty(); + } + if (!VALID_PORT_PATTERN.matcher(proxyPort).find()) { + return Optional.empty(); + } + if ((proxyUid == null) != (proxyPwd == null)) { + return Optional.empty(); + } + Map map = new HashMap<>(); + map.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, proxyHost); + map.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, proxyPort); + if (proxyUid != null) { + map.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, proxyUid); + map.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, proxyPwd); + } + return Optional.of(map); + } + + private static Optional tryParseTrustStoreFromRawUri(String connectionUri) { + try { + String path = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME); + String password = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PWD_PROPERTY_NAME); + String type = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.SSL_TRUST_STORE_TYPE_PROPERTY_NAME); + String provider = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROVIDER_PROPERTY_NAME); + return Optional.of(new TrustStoreSettings(path, password, type, provider)); + } catch (RuntimeException e) { + return Optional.empty(); + } + } + + private static HttpTransport createClearcutHttpTransport( + Map proxyProperties, + String sslTrustStorePath, + String sslTrustStorePassword, + String sslTrustStoreType, + String sslTrustStoreProvider) { + return BigQueryJdbcProxyUtility.getHttpTransportOptions( + proxyProperties, + sslTrustStorePath, + sslTrustStorePassword, + sslTrustStoreType, + sslTrustStoreProvider, + null, + null, + BigQueryJdbcDiagnosticTelemetry.class.getName()) + .getHttpTransportFactory() + .create(); + } + + static boolean isNonDefaultCredentialUniverse(Credentials credentials) { + if (credentials == null || isComputeEngineBacked(credentials)) { + return false; + } + try { + return isNonDefaultUniverse(credentials.getUniverseDomain()); + } catch (IOException e) { + return true; + } + } + + private static boolean isComputeEngineBacked(Credentials credentials) { + Credentials current = credentials; + while (current instanceof ImpersonatedCredentials) { + current = ((ImpersonatedCredentials) current).getSourceCredentials(); + } + return current instanceof ComputeEngineCredentials; + } + + private static boolean isNonDefaultUniverse(String universeDomain) { + if (!isNonBlank(universeDomain)) { + return false; + } + return !BigQueryJdbcUrlUtility.DEFAULT_UNIVERSE_DOMAIN_VALUE.equalsIgnoreCase( + universeDomain.trim()); + } + + private static boolean isNonBlank(String value) { + return value != null && !value.trim().isEmpty(); + } + + static String computeTransportProfileKey( + Map proxyProperties, + String sslTrustStorePath, + String sslTrustStorePassword, + String sslTrustStoreType, + String sslTrustStoreProvider) { + boolean hasProxy = proxyProperties.containsKey(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME); + boolean hasSsl = sslTrustStorePath != null; + if (!hasProxy && !hasSsl) { + return null; + } + Hasher hasher = Hashing.sha256().newHasher(); + putLengthPrefixed( + hasher, + hasProxy ? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME) : null); + putLengthPrefixed( + hasher, + hasProxy ? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME) : null); + putLengthPrefixed( + hasher, + hasProxy ? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME) : null); + putLengthPrefixed( + hasher, + hasProxy ? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME) : null); + putLengthPrefixed(hasher, sslTrustStorePath); + putLengthPrefixed(hasher, hasSsl ? sslTrustStorePassword : null); + putLengthPrefixed(hasher, hasSsl ? sslTrustStoreType : null); + putLengthPrefixed(hasher, hasSsl ? sslTrustStoreProvider : null); + return hasher.hash().toString(); + } + + private static void putLengthPrefixed(Hasher hasher, String value) { + if (value == null) { + hasher.putInt(-1); + return; + } + byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8); + hasher.putInt(valueBytes.length); + hasher.putBytes(valueBytes); + } + + private static final class TrustStoreSettings { + final String path; + final String password; + final String type; + final String provider; + + TrustStoreSettings(String path, String password, String type, String provider) { + this.path = path; + this.password = password; + this.type = type; + this.provider = provider; + } + } +} diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java index 24a7f6afee83..1f3b84e7de4f 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java @@ -20,12 +20,18 @@ import com.google.cloud.bigquery.BigQueryOptions; import com.google.cloud.bigquery.jdbc.utils.TestUtilities; import com.google.cloud.bigquery.jdbc.utils.URIBuilder; +import com.google.gson.JsonObject; +import java.io.File; import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; public class BigQueryJdbcBaseTest { + protected static final String CUSTOM_UNIVERSE_DOMAIN = "apis-tpczero.goog"; + // This is a fake pkcs8 key generated specifically for unittests protected static final String fake_pkcs8_key = "-----BEGIN PRIVATE KEY-----\n" @@ -101,4 +107,25 @@ protected static URIBuilder getUriOAuthApplicationDefault() { protected static URIBuilder getUriOAuthExternal() { return getBaseUri().append("OAuthType", 4).append("OAuthPvtKey", fake_pkcs8_key); } + + protected static JsonObject serviceAccountJson(String universeDomain) { + JsonObject saJson = new JsonObject(); + saJson.addProperty("type", "service_account"); + saJson.addProperty("project_id", "test-project"); + saJson.addProperty("private_key_id", "test-key-id"); + saJson.addProperty("private_key", fake_pkcs8_key); + saJson.addProperty("client_email", "test-sa@test-project.iam.gserviceaccount.com"); + saJson.addProperty("client_id", "123456789"); + saJson.addProperty("token_uri", "https://oauth2." + universeDomain + "/token"); + saJson.addProperty("universe_domain", universeDomain); + return saJson; + } + + protected static String getTestResourcePath(String resourceName) throws URISyntaxException { + URL resourceUrl = BigQueryJdbcBaseTest.class.getClassLoader().getResource(resourceName); + if (resourceUrl == null) { + throw new IllegalStateException("Test resource not found: " + resourceName); + } + return new File(resourceUrl.toURI()).getAbsolutePath(); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java new file mode 100644 index 000000000000..5a6848a4f788 --- /dev/null +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java @@ -0,0 +1,445 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.bigquery.jdbc; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.apache.v5.Apache5HttpTransport; +import com.google.auth.Credentials; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.ComputeEngineCredentials; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Level; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; + +public class BigQueryJdbcDiagnosticTelemetryTest extends BigQueryJdbcLoggingBaseTest { + + private static final String DEFAULT_UNIVERSE = "googleapis.com"; + private static final String RAW_URI_PREFIX = + "bigquery://https://www.googleapis.com/bigquery/v2:443"; + + @BeforeEach + @AfterEach + public void resetTelemetry() { + TelemetryTestUtils.reset(); + } + + @Test + public void testIsSuppressed_nonDefaultUniverseAndOverridesAndPsc() { + DataSource defaultDs = new DataSource(); + defaultDs.setUniverseDomain(DEFAULT_UNIVERSE); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(defaultDs, null)).isFalse(); + + DataSource customUniverseDs = new DataSource(); + customUniverseDs.setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(customUniverseDs, null)).isTrue(); + + DataSource endpointOverrideDs = new DataSource(); + endpointOverrideDs.setEndpointOverrides("BIGQUERY=https://override.example.com"); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(endpointOverrideDs, null)).isTrue(); + + DataSource pscDs = new DataSource(); + pscDs.setPrivateServiceConnect("BIGQUERY=https://psc.example.com"); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(pscDs, null)).isTrue(); + + DataSource blankOverridesDs = new DataSource(); + blankOverridesDs.setUniverseDomain(" GOOGLEAPIS.COM "); + blankOverridesDs.setEndpointOverrides(" "); + blankOverridesDs.setPrivateServiceConnect(""); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(blankOverridesDs, null)).isFalse(); + } + + @Test + public void testIsSuppressed_envUniverseDomainPrecedence() { + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(CUSTOM_UNIVERSE_DOMAIN); + + // Omitted explicit universe inherits non-default env universe -> suppressed + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(new DataSource(), null)).isTrue(); + + // Explicit googleapis.com overrides non-default env universe -> not suppressed + DataSource explicitDefault = new DataSource(); + explicitDefault.setUniverseDomain(DEFAULT_UNIVERSE); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(explicitDefault, null)).isFalse(); + + // Blank/null env universe behaves as default -> not suppressed + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(null); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(new DataSource(), null)).isFalse(); + } + } + + @Test + public void testIsNonDefaultCredentialUniverse_allCredentialTypes() throws Exception { + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(null)).isFalse(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + GoogleCredentials.create(new AccessToken("token", null)))) + .isFalse(); + + ServiceAccountCredentials defaultSa = buildServiceAccountCredentials(DEFAULT_UNIVERSE); + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(defaultSa)).isFalse(); + + ServiceAccountCredentials customSa = buildServiceAccountCredentials(CUSTOM_UNIVERSE_DOMAIN); + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(customSa)).isTrue(); + + ComputeEngineCredentials computeCreds = ComputeEngineCredentials.create(); + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(computeCreds)) + .isFalse(); + + ImpersonatedCredentials impersonatedFromCompute = + ImpersonatedCredentials.newBuilder() + .setSourceCredentials(computeCreds) + .setTargetPrincipal("target@test-project.iam.gserviceaccount.com") + .setScopes(Collections.singletonList("https://www.googleapis.com/auth/bigquery")) + .build(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(impersonatedFromCompute)) + .isFalse(); + + ImpersonatedCredentials impersonatedFromCustomSa = + ImpersonatedCredentials.newBuilder() + .setSourceCredentials(customSa) + .setTargetPrincipal("target@test-project.iam.gserviceaccount.com") + .setScopes(Collections.singletonList("https://www.googleapis.com/auth/bigquery")) + .build(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + impersonatedFromCustomSa)) + .isTrue(); + + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + stubCredentials(() -> null))) + .isFalse(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + stubCredentials(() -> " "))) + .isFalse(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + stubCredentials( + () -> { + throw new IOException("simulated lookup error"); + }))) + .isTrue(); + } + + @Test + public void testComputeTransportProfileKey_differentiatesAllActiveFields() { + Map empty = Collections.emptyMap(); + + // No proxy and no SSLTrustStore -> direct (null), even if unused SSLTrustStore* fields are set + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + empty, null, "unused-pwd", "PKCS12", "SUN")) + .isNull(); + + Map proxyA = proxyMap("127.0.0.1", "8080", "user1", "pass1"); + Map proxyDiffHost = proxyMap("127.0.0.2", "8080", "user1", "pass1"); + Map proxyDiffPort = proxyMap("127.0.0.1", "8081", "user1", "pass1"); + Map proxyDiffUid = proxyMap("127.0.0.1", "8080", "user2", "pass1"); + Map proxyDiffPwd = proxyMap("127.0.0.1", "8080", "user1", "pass2"); + + String keyA = + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/ts.jks", "pwd1", "JKS", "SUN"); + assertThat(keyA).isNotNull(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/ts.jks", "pwd1", "JKS", "SUN")) + .isEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyDiffHost, "/ts.jks", "pwd1", "JKS", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyDiffPort, "/ts.jks", "pwd1", "JKS", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyDiffUid, "/ts.jks", "pwd1", "JKS", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyDiffPwd, "/ts.jks", "pwd1", "JKS", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/other.jks", "pwd1", "JKS", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/ts.jks", "pwd2", "JKS", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/ts.jks", "pwd1", "PKCS12", "SUN")) + .isNotEqualTo(keyA); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/ts.jks", "pwd1", "JKS", "BC")) + .isNotEqualTo(keyA); + + // Unused SSLTrustStore* fields with proxy-only config produce the same key + String proxyOnlyA = + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, null, "ignored", "PKCS12", "SUN"); + String proxyOnlyB = + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey(proxyA, null, null, null, null); + assertThat(proxyOnlyA).isEqualTo(proxyOnlyB); + } + + @Test + public void testTryParseProxyPropertiesSilently_validAndMalformedWithoutSevereLogs() { + capturedLogs.clear(); + + // No proxy configured -> empty map + assertThat(BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(new DataSource())) + .isEqualTo(Optional.of(Collections.emptyMap())); + + // Valid authenticated proxy + DataSource validDs = new DataSource(); + validDs.setProxyHost("127.0.0.1"); + validDs.setProxyPort("8080"); + validDs.setProxyUid("user"); + validDs.setProxyPwd("pass"); + Optional> valid = + BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(validDs); + assertThat(valid.isPresent()).isTrue(); + assertThat(valid.get()).containsEntry("ProxyHost", "127.0.0.1"); + assertThat(valid.get()).containsEntry("ProxyPort", "8080"); + assertThat(valid.get()).containsEntry("ProxyUid", "user"); + assertThat(valid.get()).containsEntry("ProxyPwd", "pass"); + + // Blank ProxyHost -> Optional.empty() + DataSource blankHost = new DataSource(); + blankHost.setProxyHost(" "); + blankHost.setProxyPort("8080"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(blankHost).isPresent()) + .isFalse(); + + // Missing ProxyPort -> Optional.empty() + DataSource missingPort = new DataSource(); + missingPort.setProxyHost("127.0.0.1"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(missingPort) + .isPresent()) + .isFalse(); + + // Invalid port -> Optional.empty() + DataSource badPort = new DataSource(); + badPort.setProxyHost("127.0.0.1"); + badPort.setProxyPort("99999"); + assertThat(BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(badPort).isPresent()) + .isFalse(); + + // Auth without password -> Optional.empty() + DataSource missingPwd = new DataSource(); + missingPwd.setProxyHost("127.0.0.1"); + missingPwd.setProxyPort("8080"); + missingPwd.setProxyUid("user"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(missingPwd).isPresent()) + .isFalse(); + + // Auth without host -> Optional.empty() + DataSource authOnly = new DataSource(); + authOnly.setProxyUid("user"); + authOnly.setProxyPwd("pass"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.tryParseProxyPropertiesSilently(authOnly).isPresent()) + .isFalse(); + + boolean anySevere = capturedLogs.stream().anyMatch(r -> r.getLevel() == Level.SEVERE); + assertThat(anySevere).isFalse(); + } + + @Test + public void testRecordFailedConnection_rawUriWithValidProxyAndTrustStoreInitializesApache5() + throws Exception { + String trustStorePath = getTestResourcePath("localhost-truststore.jks"); + String rawUri = + RAW_URI_PREFIX + + ";OAuthType=invalid;ProxyHost=127.0.0.1;ProxyPort=8080;" + + "SSLTrustStore=" + + trustStorePath + + ";SSLTrustStorePwd=changeit;"; + + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()) + .isInstanceOf(Apache5HttpTransport.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "EnableDiagnosticTelemetry=0;SSLTrustStorePwd=my%pass;", + "universeDomain=apis-tpczero.goog;SSLTrustStorePwd=my%pass;", + "EndpointOverrides=https://bad%escape.example.com;", + "PrivateServiceConnectUris=https://bad%escape.example.com;", + "universeDomain=bad%escape;", + "EnableDiagnosticTelemetry=bad%escape;" + }) + public void testRecordFailedConnection_rawUriMalformedPercentStillDisablesActiveManager( + String rawSuffix) { + assertThat(TelemetryManager.getInstance()).isNotNull(); + assertThat(TelemetryManager.isInitialized()).isTrue(); + + String rawUri = RAW_URI_PREFIX + ";" + rawSuffix; + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "ProxyHost=127.0.0.1;", + "ProxyHost= ;ProxyPort=8080;", + "ProxyHost=127.0.0.1;ProxyPort=8080;ProxyPwd=bad%pass;", + "SSLTrustStorePwd=bad%pass;" + }) + public void testRecordFailedConnection_rawUriMalformedTransportSkipsInitWithoutKillingActive( + String rawTransportSuffix) { + // Fresh JVM: malformed raw transport never initializes a direct fallback manager + String rawUri = RAW_URI_PREFIX + ";" + rawTransportSuffix; + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + + // Active proxied manager: malformed raw transport leaves it intact without disabling + HttpTransport activeProxyTransport = initActiveProxiedManager(); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(activeProxyTransport); + } + + @Test + public void testRecordFailedConnection_parsedDataSourceOptOutDisablesActiveManager() { + initActiveProxiedManager(); + + DataSource optOutMalformedProxyDs = new DataSource(); + optOutMalformedProxyDs.setEnableDiagnosticTelemetry(false); + optOutMalformedProxyDs.setProxyHost("127.0.0.1"); + + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + RAW_URI_PREFIX, + optOutMalformedProxyDs, + AuthenticationType.AUTHENTICATION_TYPE_TOKEN, + new IllegalArgumentException("missing ProxyPort")); + + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + private static HttpTransport initActiveProxiedManager() { + HttpTransport activeTransport = mock(HttpTransport.class); + assertThat( + TelemetryManager.getInstance( + new Properties(), "proxy-profile", () -> activeTransport, false)) + .isNotNull(); + return activeTransport; + } + + private static Map proxyMap(String host, String port, String uid, String pwd) { + Map map = new HashMap<>(); + map.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, host); + map.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, port); + map.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, uid); + map.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, pwd); + return map; + } + + private static ServiceAccountCredentials buildServiceAccountCredentials(String universeDomain) + throws IOException { + return ServiceAccountCredentials.fromStream( + new ByteArrayInputStream( + serviceAccountJson(universeDomain).toString().getBytes(StandardCharsets.UTF_8))); + } + + @FunctionalInterface + private interface UniverseSupplier { + String get() throws IOException; + } + + private static Credentials stubCredentials(UniverseSupplier universeSupplier) { + return new Credentials() { + @Override + public String getAuthenticationType() { + return "test"; + } + + @Override + public Map> getRequestMetadata(URI uri) { + return Collections.emptyMap(); + } + + @Override + public boolean hasRequestMetadata() { + return false; + } + + @Override + public boolean hasRequestMetadataOnly() { + return false; + } + + @Override + public void refresh() {} + + @Override + public String getUniverseDomain() throws IOException { + return universeSupplier.get(); + } + }; + } +} diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java index 1ccbe13bbe4d..10285e27e9e6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java @@ -395,6 +395,43 @@ public void testParseDiagnosticTelemetryProperties() { DataSource defaultDs = DataSource.fromUrl(urlWithoutTelemetry); assertThat(defaultDs.getEnableDiagnosticTelemetry()) .isEqualTo(TelemetryPropertyUtility.DEFAULT_ENABLE_DIAGNOSTIC_TELEMETRY_VALUE); + assertThat(defaultDs.createProperties().getProperty("EnableDiagnosticTelemetry")).isNull(); + } + + @Test + public void testDataSourceCreateProperties_serializesOverridesAndOmitsUnsetDiagnosticTelemetry() { + DataSource ds = new DataSource(); + ds.setEndpointOverrides("BIGQUERY=https://override.example.com"); + ds.setPrivateServiceConnect("BIGQUERY=https://psc.example.com"); + + Properties props = ds.createProperties(); + assertThat(props.getProperty("EnableDiagnosticTelemetry")).isNull(); + assertThat(props.getProperty("EndpointOverrides")) + .isEqualTo("BIGQUERY=https://override.example.com"); + assertThat(props.getProperty("PrivateServiceConnectUris")) + .isEqualTo("BIGQUERY=https://psc.example.com"); + + ds.setEnableDiagnosticTelemetry(true); + assertThat(ds.createProperties().getProperty("EnableDiagnosticTelemetry")).isEqualTo("true"); + } + + @Test + public void testParseLastUriPropertyWithoutValidation_returnsLastMatchingValue() { + String uri = + "bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "EnableDiagnosticTelemetry=1;universeDomain=googleapis.com;" + + "enablediagnostictelemetry=0;UNIVERSEDOMAIN=apis-tpczero.goog"; + + assertThat( + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + uri, "EnableDiagnosticTelemetry")) + .isEqualTo("0"); + assertThat(BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(uri, "universeDomain")) + .isEqualTo("apis-tpczero.goog"); + assertThat(BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(uri, "Absent")) + .isNull(); + assertThat(BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(null, "universeDomain")) + .isNull(); } @Test From 47561a9abe438a2efc699dbef82d05b080367710 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 16:30:14 +0000 Subject: [PATCH 2/5] fix(bigquery-jdbc): add last-wins raw URI property parser for Clearcut failed-connect path --- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index 6c34cddfec06..832cdd3ba273 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -768,9 +768,23 @@ static String parseUriProperty(String uri, String property) { * @return The String value of the property, or null if the property is not found. */ static String parseUriPropertyWithoutValidation(String uri, String property) { + return parseUriPropertyWithoutValidation(uri, property, false); + } + + /** + * Parses the last matching value for {@code property} from the URI without validating other + * properties, matching last-wins precedence when {@link Properties} are appended to the URL. + */ + static String parseLastUriPropertyWithoutValidation(String uri, String property) { + return parseUriPropertyWithoutValidation(uri, property, true); + } + + private static String parseUriPropertyWithoutValidation( + String uri, String property, boolean lastWins) { if (uri == null) { return null; } + String rawMatchedValue = null; int start = 0; int len = uri.length(); while (start < len) { @@ -781,14 +795,19 @@ static String parseUriPropertyWithoutValidation(String uri, String property) { if (eqIndex > start && eqIndex < end) { String key = uri.substring(start, eqIndex).trim(); if (key.equalsIgnoreCase(property)) { - String value = uri.substring(eqIndex + 1, end); - return CharEscapers.decodeUriPath(value.replace("+", "%2B")); + rawMatchedValue = uri.substring(eqIndex + 1, end); + if (!lastWins) { + return CharEscapers.decodeUriPath(rawMatchedValue.replace("+", "%2B")); + } } } start = end + 1; } - return null; + if (rawMatchedValue == null) { + return null; + } + return CharEscapers.decodeUriPath(rawMatchedValue.replace("+", "%2B")); } /** From fce6159adc5b82c5ed433b844fe6c1145dd3e580 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 16:31:48 +0000 Subject: [PATCH 3/5] test(bigquery-jdbc): add driver Clearcut suppression, proxy/TLS, and profile isolation tests --- .../bigquery/jdbc/BigQueryDriverTest.java | 647 ++++++++++++++++++ 1 file changed, 647 insertions(+) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java index dde6b644e1e6..2e561665d51c 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java @@ -24,36 +24,71 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.apache.v5.Apache5HttpTransport; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; +import com.google.cloud.bigquery.jdbc.telemetry.v1.LogRequest; import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPayload; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; import com.google.cloud.bigquery.jdbc.utils.BigQueryJdbcVersionUtility; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; import io.opentelemetry.api.OpenTelemetry; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.security.KeyStore; import java.sql.Connection; import java.sql.DriverPropertyInfo; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.MockedStatic; public class BigQueryDriverTest extends BigQueryJdbcLoggingBaseTest { static BigQueryDriver bigQueryDriver; + private static final String PROXY_USER = "proxyuser"; + private static final String PROXY_PASS = "proxypass"; + private static final String EXPECTED_PROXY_AUTH = + "Basic " + + Base64.getEncoder() + .encodeToString((PROXY_USER + ":" + PROXY_PASS).getBytes(StandardCharsets.UTF_8)); /** Token-auth URL that connects without network access; shared by the telemetry tests. */ private static final String VALID_TOKEN_URL = @@ -414,4 +449,616 @@ public void testAllowUrlLogPathFalseBlocksUrlAndPropertiesLogPath(@TempDir Path } } } + + @ParameterizedTest + @CsvSource({ + "universeDomain, apis-tpczero.goog", + "EndpointOverrides, BIGQUERY=https://override.example.com", + "PrivateServiceConnectUris, BIGQUERY=https://psc.example.com" + }) + public void testConnect_suppressesClearcutForUrlPropertyOnSuccessAndFailure( + String propertyName, String propertyValue) throws SQLException { + String successUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append(propertyName, propertyValue) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection conn = bigQueryDriver.connect(successUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + + TelemetryTestUtils.reset(); + String failedUrl = + getBaseUri() + .append("OAuthType", "invalid") + .append(propertyName, propertyValue) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + Assertions.assertThrows( + SQLException.class, () -> bigQueryDriver.connect(failedUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"universeDomain", "EndpointOverrides", "PrivateServiceConnectUris"}) + public void testDataSource_suppressesClearcutForRealmOrOverrideSetter(String setter) + throws SQLException { + DataSource ds = new DataSource(); + ds.setURL( + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 1) + .toString()); + if ("universeDomain".equals(setter)) { + ds.setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN); + } else if ("EndpointOverrides".equals(setter)) { + ds.setEndpointOverrides("BIGQUERY=https://override.example.com"); + } else { + ds.setPrivateServiceConnect("BIGQUERY=https://psc.example.com"); + } + + try (Connection conn = ds.getConnection()) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @Test + public void testConnect_customUniverseServiceAccountKeySuppressesOnSuccess(@TempDir Path tempDir) + throws Exception { + Path keyFile = writeServiceAccountJson(tempDir, CUSTOM_UNIVERSE_DOMAIN); + String url = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + try (Connection conn = bigQueryDriver.connect(url, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @Test + public void testConnect_customUniverseServiceAccountKeySuppressesOnPostCredentialFailure( + @TempDir Path tempDir) throws Exception { + Path keyFile = writeServiceAccountJson(tempDir, CUSTOM_UNIVERSE_DOMAIN); + String url = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .append("DefaultDataset", "invalid:") + .toString(); + + Assertions.assertThrows( + BigQueryJdbcRuntimeException.class, () -> bigQueryDriver.connect(url, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @Test + public void testDirectConnection_customUniverseServiceAccountKeyDisablesActiveManager( + @TempDir Path tempDir) throws Exception { + try (Connection commercial = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + Path keyFile = writeServiceAccountJson(tempDir, CUSTOM_UNIVERSE_DOMAIN); + String url = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + try (BigQueryConnection direct = new BigQueryConnection(url)) { + assertThat(direct.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @Test + public void testConnect_preCredentialFailureFollowedByCustomUniverseKeyDropsQueuedBatch( + @TempDir Path tempDir) throws Exception { + List captured = Collections.synchronizedList(new ArrayList<>()); + TelemetryTestUtils.initCapturingPayloads(captured); + + // Pre-credential failure queues a failed connection attempt on the active batcher + String missingKeyUrl = getBaseUri(0, "test-project").toString(); + Assertions.assertThrows( + BigQueryJdbcRuntimeException.class, + () -> bigQueryDriver.connect(missingKeyUrl, new Properties())); + + // Subsequent connect with custom-universe key disables globally and drops buffered events + Path keyFile = writeServiceAccountJson(tempDir, CUSTOM_UNIVERSE_DOMAIN); + String customSaUrl = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection conn = bigQueryDriver.connect(customSaUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + assertThat(captured).isEmpty(); + } + + @Test + public void testConnect_activeCommercialTelemetryDisabledBySubsequentSuppressedConnection() + throws SQLException { + try (Connection commercial = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + + String suppressedUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("universeDomain", CUSTOM_UNIVERSE_DOMAIN) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection nonDefault = bigQueryDriver.connect(suppressedUrl, new Properties())) { + assertThat(nonDefault.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + + // Global kill switch remains latched for subsequent commercial connections + try (Connection commercialAgain = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(commercialAgain.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + @Test + public void testDataSource_urlOptOutNotClobberedByDefaultDataSource() throws SQLException { + DataSource ds = new DataSource(); + ds.setURL( + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 0) + .toString()); + + try (Connection conn = ds.getConnection()) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + @Test + public void testConnect_enableDiagnosticTelemetryPropertiesOverrideUrl() throws SQLException { + // URL=1 overridden by Properties=0 -> disabled + String urlEnabled = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + Properties disableProps = new Properties(); + disableProps.setProperty("EnableDiagnosticTelemetry", "0"); + try (Connection conn = bigQueryDriver.connect(urlEnabled, disableProps)) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + + // URL=0 overridden by Properties=1 -> enabled (consistent with DataSource last-wins) + TelemetryTestUtils.reset(); + String urlDisabled = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 0) + .toString(); + Properties enableProps = new Properties(); + enableProps.setProperty("EnableDiagnosticTelemetry", "1"); + try (Connection conn = bigQueryDriver.connect(urlDisabled, enableProps)) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + + @Test + public void testConnect_nullUrlDoesNotInitializeTelemetry() { + Assertions.assertThrows(BigQueryJdbcException.class, () -> bigQueryDriver.connect(null, null)); + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + @Test + public void testConnect_invalidProxyOrTrustStoreOnFailure_neverFallsBackToDirectTransport() + throws SQLException { + String missingPortUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .toString(); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> bigQueryDriver.connect(missingPortUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + + TelemetryTestUtils.reset(); + String missingTrustStoreUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("SSLTrustStore", "/nonexistent/path/truststore.jks") + .toString(); + Assertions.assertThrows( + BigQueryJdbcRuntimeException.class, + () -> bigQueryDriver.connect(missingTrustStoreUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + + // Failed connect with suppressed universe + malformed proxy still disables active manager + TelemetryTestUtils.reset(); + try (Connection commercial = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + String suppressedBadProxyUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("universeDomain", CUSTOM_UNIVERSE_DOMAIN) + .append("ProxyHost", "127.0.0.1") + .toString(); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> bigQueryDriver.connect(suppressedBadProxyUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + @Test + public void testConnect_failedMalformedProxyDoesNotDisableActiveProxiedManager() + throws Exception { + String trustStorePath = getTestResourcePath("localhost-truststore.jks"); + String validProxiedUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", 8080) + .append("SSLTrustStore", trustStorePath) + .append("SSLTrustStorePwd", "changeit") + .toString(); + try (Connection proxied = bigQueryDriver.connect(validProxiedUrl, new Properties())) { + assertThat(proxied.isClosed()).isFalse(); + } + HttpTransport activeTransport = TelemetryTestUtils.getActiveHttpTransport(); + assertThat(activeTransport).isInstanceOf(Apache5HttpTransport.class); + + // Commercial failed connect with missing ProxyPort must not spuriously kill active proxied mgr + String malformedProxyUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .toString(); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> bigQueryDriver.connect(malformedProxyUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(activeTransport); + } + + @Test + public void testConnect_authenticatedProxyAndTrustStore_routesClearcutAndReusesTransport() + throws Exception { + String trustStorePath = getTestResourcePath("localhost-truststore.jks"); + try (LoopbackHttpsServer httpsServer = new LoopbackHttpsServer(); + LoopbackConnectProxy proxy = new LoopbackConnectProxy(EXPECTED_PROXY_AUTH)) { + String proxiedUrl = buildProxiedUrl(proxy.getPort(), PROXY_USER, PROXY_PASS, trustStorePath); + + try (Connection conn1 = bigQueryDriver.connect(proxiedUrl, new Properties())) { + assertThat(conn1.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isTrue(); + HttpTransport firstTransport = TelemetryTestUtils.getActiveHttpTransport(); + assertThat(firstTransport).isInstanceOf(Apache5HttpTransport.class); + + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + httpsServer.getEndpointUrl(), TelemetryPayload.getDefaultInstance())) + .isTrue(); + assertThat(proxy.getAuthorizedConnects()).isEqualTo(1); + assertThat(httpsServer.getHitCount()).isEqualTo(1); + LogRequest decoded = LogRequest.parseFrom(httpsServer.getLastBody()); + assertThat(decoded.getLogEventsCount()).isEqualTo(1); + + // Identical proxy + TrustStore reuses the exact same transport instance + try (Connection conn2 = bigQueryDriver.connect(proxiedUrl, new Properties())) { + assertThat(conn2.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(firstTransport); + } + } + + @Test + public void testConnect_conflictingProxyUserOrDirectProfile_disablesActiveTelemetry() + throws Exception { + String trustStorePath = getTestResourcePath("localhost-truststore.jks"); + String proxiedUser1 = buildProxiedUrl(8080, PROXY_USER, PROXY_PASS, trustStorePath); + String proxiedUser2 = buildProxiedUrl(8080, "otheruser", PROXY_PASS, trustStorePath); + + // Different proxy user disables active proxied manager + try (Connection conn1 = bigQueryDriver.connect(proxiedUser1, new Properties())) { + assertThat(conn1.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isTrue(); + try (Connection conn2 = bigQueryDriver.connect(proxiedUser2, new Properties())) { + assertThat(conn2.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + + // Direct connection after proxied connection also disables active proxied manager + TelemetryTestUtils.reset(); + try (Connection conn1 = bigQueryDriver.connect(proxiedUser1, new Properties())) { + assertThat(conn1.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isTrue(); + try (Connection direct = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(direct.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + @Test + public void testConnect_wrongProxyCredentials_failsClearcutUploadSilently() throws Exception { + String trustStorePath = getTestResourcePath("localhost-truststore.jks"); + try (LoopbackHttpsServer httpsServer = new LoopbackHttpsServer(); + LoopbackConnectProxy proxy = new LoopbackConnectProxy(EXPECTED_PROXY_AUTH)) { + String wrongAuthUrl = + buildProxiedUrl(proxy.getPort(), PROXY_USER, "wrongpass", trustStorePath); + + try (Connection conn = bigQueryDriver.connect(wrongAuthUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + httpsServer.getEndpointUrl(), TelemetryPayload.getDefaultInstance())) + .isFalse(); + assertThat(httpsServer.getHitCount()).isEqualTo(0); + } + } + + @Test + public void testConnect_missingTrustStoreThroughProxy_failsTlsSilently() throws Exception { + try (LoopbackHttpsServer httpsServer = new LoopbackHttpsServer(); + LoopbackConnectProxy proxy = new LoopbackConnectProxy(EXPECTED_PROXY_AUTH)) { + String noTrustStoreUrl = buildProxiedUrl(proxy.getPort(), PROXY_USER, PROXY_PASS, null); + + try (Connection conn = bigQueryDriver.connect(noTrustStoreUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + httpsServer.getEndpointUrl(), TelemetryPayload.getDefaultInstance())) + .isFalse(); + assertThat(httpsServer.getHitCount()).isEqualTo(0); + } + } + + @Test + public void testConnect_unreachableProxyPort_failsClearcutUploadSilently() throws Exception { + int unusedPort; + try (ServerSocket closedSocket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + unusedPort = closedSocket.getLocalPort(); + } + String deadProxyUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", unusedPort) + .toString(); + + try (Connection conn = bigQueryDriver.connect(deadProxyUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + "https://localhost:443/log", TelemetryPayload.getDefaultInstance())) + .isFalse(); + } + + private String buildProxiedUrl( + int proxyPort, String proxyUid, String proxyPwd, String trustStorePath) { + URIBuilder builder = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", proxyPort) + .append("ProxyUid", proxyUid) + .append("ProxyPwd", proxyPwd); + if (trustStorePath != null) { + builder.append("SSLTrustStore", trustStorePath).append("SSLTrustStorePwd", "changeit"); + } + return builder.toString(); + } + + private static Path writeServiceAccountJson(Path dir, String universeDomain) throws IOException { + Path file = dir.resolve("sa-" + universeDomain + ".json"); + Files.write( + file, serviceAccountJson(universeDomain).toString().getBytes(StandardCharsets.UTF_8)); + return file; + } + + /** Loopback HTTPS server accepting Clearcut POST payloads on {@code /log}. */ + private static final class LoopbackHttpsServer implements AutoCloseable { + private final HttpsServer server; + private final AtomicInteger hitCount = new AtomicInteger(0); + private final AtomicReference lastBody = new AtomicReference<>(); + + LoopbackHttpsServer() throws Exception { + KeyStore serverKeyStore = KeyStore.getInstance("JKS"); + try (InputStream ksStream = + BigQueryDriverTest.class.getResourceAsStream("/localhost-keystore.jks")) { + serverKeyStore.load(ksStream, "changeit".toCharArray()); + } + KeyManagerFactory kmf = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(serverKeyStore, "changeit".toCharArray()); + SSLContext serverSslContext = SSLContext.getInstance("TLS"); + serverSslContext.init(kmf.getKeyManagers(), null, null); + + this.server = + HttpsServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + this.server.setHttpsConfigurator(new HttpsConfigurator(serverSslContext)); + this.server.createContext( + "/log", + exchange -> { + hitCount.incrementAndGet(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int read; + try (InputStream in = exchange.getRequestBody()) { + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + } + lastBody.set(out.toByteArray()); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + this.server.start(); + } + + String getEndpointUrl() { + return "https://localhost:" + server.getAddress().getPort() + "/log"; + } + + int getHitCount() { + return hitCount.get(); + } + + byte[] getLastBody() { + return lastBody.get(); + } + + @Override + public void close() { + server.stop(0); + } + } + + /** Minimal loopback HTTP CONNECT proxy requiring Basic Proxy-Authorization for unit tests. */ + private static final class LoopbackConnectProxy implements AutoCloseable { + private final ServerSocket serverSocket; + private final String expectedProxyAuth; + private final AtomicInteger authorizedConnects = new AtomicInteger(0); + private volatile boolean running = true; + + LoopbackConnectProxy(String expectedProxyAuth) throws IOException { + this.serverSocket = new ServerSocket(0, 16, InetAddress.getLoopbackAddress()); + this.expectedProxyAuth = expectedProxyAuth; + Thread acceptThread = new Thread(this::acceptLoop, "test-loopback-connect-proxy"); + acceptThread.setDaemon(true); + acceptThread.start(); + } + + int getPort() { + return serverSocket.getLocalPort(); + } + + int getAuthorizedConnects() { + return authorizedConnects.get(); + } + + private void acceptLoop() { + while (running) { + try { + Socket client = serverSocket.accept(); + Thread handler = + new Thread(() -> handleClient(client), "test-loopback-connect-proxy-client"); + handler.setDaemon(true); + handler.start(); + } catch (IOException e) { + if (!running) { + return; + } + } + } + } + + private void handleClient(Socket client) { + try (Socket clientSocket = client) { + BufferedReader reader = + new BufferedReader( + new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.US_ASCII)); + String requestLine = reader.readLine(); + if (requestLine == null || !requestLine.startsWith("CONNECT ")) { + return; + } + String authority = requestLine.split(" ")[1]; + int colon = authority.lastIndexOf(':'); + int targetPort = Integer.parseInt(authority.substring(colon + 1)); + + String proxyAuth = null; + String headerLine; + while ((headerLine = reader.readLine()) != null && !headerLine.isEmpty()) { + int idx = headerLine.indexOf(':'); + if (idx > 0 + && headerLine.substring(0, idx).trim().equalsIgnoreCase("Proxy-Authorization")) { + proxyAuth = headerLine.substring(idx + 1).trim(); + } + } + + OutputStream clientOut = clientSocket.getOutputStream(); + if (!expectedProxyAuth.equals(proxyAuth)) { + clientOut.write( + ("HTTP/1.1 407 Proxy Authentication Required\r\n" + + "Proxy-Authenticate: Basic realm=\"test\"\r\n" + + "Content-Length: 0\r\n" + + "Connection: close\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII)); + clientOut.flush(); + return; + } + + authorizedConnects.incrementAndGet(); + try (Socket upstream = new Socket(InetAddress.getLoopbackAddress(), targetPort)) { + clientOut.write( + "HTTP/1.1 200 Connection Established\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + clientOut.flush(); + + Thread upstreamToClient = + new Thread( + () -> copyQuietly(upstream, clientSocket), + "test-loopback-proxy-upstream-to-client"); + upstreamToClient.setDaemon(true); + upstreamToClient.start(); + copyQuietly(clientSocket, upstream); + upstreamToClient.join(5_000); + } + } catch (IOException | InterruptedException ignored) { + // Expected on socket shutdown or TLS rejection + } + } + + private static void copyQuietly(Socket from, Socket to) { + byte[] buffer = new byte[4096]; + try { + InputStream in = from.getInputStream(); + OutputStream out = to.getOutputStream(); + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + out.flush(); + } + } catch (IOException ignored) { + // Tunnel closed + } finally { + try { + to.shutdownOutput(); + } catch (IOException ignored) { + // Already closed + } + } + } + + @Override + public void close() throws IOException { + running = false; + serverSocket.close(); + } + } } From ad0486c79569b6f535ecf08e46f8bd88652a8ceb Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 16:33:52 +0000 Subject: [PATCH 4/5] fix(bigquery-jdbc): serialize overrides and omit unset EnableDiagnosticTelemetry in DataSource --- .../google/cloud/bigquery/jdbc/DataSource.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java index 61f5ac9f581a..9ac05e99fdf6 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java @@ -584,6 +584,14 @@ Properties createProperties() { connectionProperties.setProperty( BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, this.universeDomain); } + if (this.endpointOverrides != null) { + connectionProperties.setProperty( + BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME, this.endpointOverrides); + } + if (this.privateServiceConnect != null) { + connectionProperties.setProperty( + BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME, this.privateServiceConnect); + } if (this.proxyHost != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, this.proxyHost); @@ -750,9 +758,11 @@ Properties createProperties() { BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME, String.valueOf(this.enableGraphMetadata)); } - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, - String.valueOf(getEnableDiagnosticTelemetry())); + if (this.enableDiagnosticTelemetry != null) { + connectionProperties.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + String.valueOf(this.enableDiagnosticTelemetry)); + } return connectionProperties; } From 7503a78c3c5b3cdbe1e7cc29019727b848fe7062 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 16:36:21 +0000 Subject: [PATCH 5/5] fix(bigquery-jdbc): initialize Clearcut diagnostic telemetry after credential resolution in BigQueryConnection --- .../java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index 702b3c690df9..58d4d41041db 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -420,6 +420,8 @@ static String maskPropertyValue(String key, Object value) { this.reqGoogleDriveScope, httpTransportFactory, this.connectionClassName); + BigQueryJdbcDiagnosticTelemetry.initializeOrDisable( + ds, this.proxyProperties, this.credentials); this.defaultDataset = BigQueryJdbcUrlUtility.parseDefaultDataset(ds.getDefaultDataset()); this.location = ds.getLocation(); this.enableHighThroughputAPI = ds.getEnableHighThroughputAPI();