From 5af4bd1a25c5dead72d451afc979dc588ab56615 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:19:06 +0000 Subject: [PATCH 1/7] fix(bigquery-jdbc): pass parsed proxy properties into diagnostic telemetry initialization --- .../com/google/cloud/bigquery/jdbc/BigQueryConnection.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 484a6990fdad..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,7 +420,8 @@ static String maskPropertyValue(String key, Object value) { this.reqGoogleDriveScope, httpTransportFactory, this.connectionClassName); - BigQueryJdbcDiagnosticTelemetry.initializeOrDisable(ds, this.credentials); + BigQueryJdbcDiagnosticTelemetry.initializeOrDisable( + ds, this.proxyProperties, this.credentials); this.defaultDataset = BigQueryJdbcUrlUtility.parseDefaultDataset(ds.getDefaultDataset()); this.location = ds.getLocation(); this.enableHighThroughputAPI = ds.getEnableHighThroughputAPI(); From d5d3bc6bddd6cf0feb91002d27598ce34b260061 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:20:50 +0000 Subject: [PATCH 2/7] fix(bigquery-jdbc): shut down owned Clearcut transport and isolate transport profiles --- .../jdbc/telemetry/v1/ClearcutTransport.java | 23 +- .../jdbc/telemetry/v1/TelemetryBatcher.java | 8 + .../jdbc/telemetry/v1/TelemetryManager.java | 240 ++++++++++++++++-- 3 files changed, 241 insertions(+), 30 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransport.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransport.java index 660efde8ea13..15b068c08ce3 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransport.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransport.java @@ -23,14 +23,14 @@ import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.javanet.NetHttpTransport; import com.google.cloud.bigquery.jdbc.BigQueryJdbcCustomLogger; +import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; -final class ClearcutTransport { +final class ClearcutTransport implements AutoCloseable { private static final Logger logger = new BigQueryJdbcCustomLogger(ClearcutTransport.class.getName()); private static final String CONTENT_TYPE_PROTOBUF = "application/x-protobuf"; @@ -41,17 +41,26 @@ final class ClearcutTransport { private final TelemetryConfiguration config; private final HttpRequestFactory requestFactory; - ClearcutTransport(TelemetryConfiguration config) { - this(new NetHttpTransport(), config); - } - - // Package-private constructor for testing overrides ClearcutTransport(HttpTransport httpTransport, TelemetryConfiguration config) { this.httpTransport = httpTransport; this.config = config; this.requestFactory = this.httpTransport.createRequestFactory(); } + @VisibleForTesting + HttpTransport getHttpTransport() { + return httpTransport; + } + + @Override + public void close() { + try { + httpTransport.shutdown(); + } catch (Throwable t) { + logger.log(Level.FINE, "Error shutting down Clearcut HTTP transport", t); + } + } + TransportResult send(TelemetryPayload payload) { if (!config.isEnabled()) { return TransportResult.disabled(); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcher.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcher.java index 4d55f6d1dc8c..c9d364ef2dbf 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcher.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcher.java @@ -127,6 +127,11 @@ TelemetryConfiguration getConfig() { return config; } + @VisibleForTesting + ClearcutTransport getTransport() { + return transport; + } + private boolean isConfigured() { return config != null && config.isEnabled() && transport != null; } @@ -161,6 +166,9 @@ void close(boolean flush) { executorService.shutdownNow(); } } + if (transport != null) { + transport.close(); + } } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java index af674acd856a..29ca6cc699f5 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java @@ -16,15 +16,20 @@ package com.google.cloud.bigquery.jdbc.telemetry.v1; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.core.InternalApi; import com.google.api.gax.rpc.ApiException; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.JobStatistics.QueryStatistics; import com.google.cloud.bigquery.jdbc.BigQueryJdbcCustomLogger; +import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Descriptors.EnumValueDescriptor; import java.sql.SQLException; +import java.util.Objects; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -44,43 +49,184 @@ public final class TelemetryManager implements AutoCloseable { private static final AtomicBoolean SHUTDOWN_HOOK_REGISTERED = new AtomicBoolean(false); private final TelemetryBatcher batcher; + private final String transportProfileKey; + private volatile boolean provisional; - private TelemetryManager(TelemetryBatcher batcher) { + private TelemetryManager( + TelemetryBatcher batcher, String transportProfileKey, boolean provisional) { this.batcher = batcher; + this.transportProfileKey = transportProfileKey; + this.provisional = provisional; } /** - * Initializes or replaces the shared {@link TelemetryManager} instance with default configuration - * and transport. + * Returns the active {@link TelemetryManager} instance, or initializes a default instance if none + * is active and diagnostic telemetry is enabled. */ public static TelemetryManager getInstance() { return getInstance(null); } + /** + * Returns the active {@link TelemetryManager} instance or initializes a default instance using + * the given opt-out properties. + */ public static TelemetryManager getInstance(Properties properties) { if (globallyDisabled) { return null; } TelemetryConfiguration preliminaryConfig = TelemetryConfiguration.builder().resolveProperties(properties).build(); - return initializeWithConfig(preliminaryConfig); + if (!preliminaryConfig.isEnabled()) { + disableGlobally("opt-out configuration"); + return null; + } + + TelemetryManager localRef = instance; + if (localRef != null) { + return localRef; + } + + TelemetryManager candidate = createManager(preliminaryConfig, null, null, false); + if (candidate == null) { + return null; + } + + TelemetryManager active; + boolean closeCandidate = false; + synchronized (TelemetryManager.class) { + if (globallyDisabled) { + active = null; + closeCandidate = true; + } else if (instance != null) { + active = instance; + closeCandidate = true; + } else { + // Registered before the instance is published so that a non-null instance always implies a + // registered shutdown hook. + registerShutdownHook(); + instance = candidate; + active = candidate; + } + } + if (closeCandidate) { + closeQuietly(candidate, false); + } + return active; } /** - * Initializes or returns the shared {@link TelemetryManager} instance using a typed connection - * opt-out flag, or permanently disables diagnostic telemetry for the JVM when disabled. + * Initializes or returns the shared {@link TelemetryManager} instance for an established + * connection using its typed opt-out flag and transport profile. + * + *

Diagnostic telemetry is permanently disabled for the JVM if the resolved configuration + * disables it or if an established active instance was initialized with a different proxy or SSL + * TrustStore transport profile. A provisional instance created by an earlier failed connection + * with a different profile is replaced without flushing. */ @InternalApi - public static TelemetryManager initializeForConnection(Boolean enabledOverride) { + public static TelemetryManager initializeForConnection( + Boolean enabledOverride, + String transportProfileKey, + Supplier httpTransportSupplier) { if (globallyDisabled) { return null; } TelemetryConfiguration preliminaryConfig = TelemetryConfiguration.builder().resolveEnabled(enabledOverride).build(); - return initializeWithConfig(preliminaryConfig); + if (!preliminaryConfig.isEnabled()) { + disableGlobally("opt-out configuration"); + return null; + } + + TelemetryManager localRef = instance; + if (localRef != null) { + if (Objects.equals(localRef.transportProfileKey, transportProfileKey)) { + if (!localRef.provisional) { + return localRef; + } + synchronized (TelemetryManager.class) { + if (globallyDisabled) { + return null; + } + if (instance == localRef) { + localRef.provisional = false; + return localRef; + } + } + localRef = instance; + } + if (localRef != null && !localRef.provisional) { + if (Objects.equals(localRef.transportProfileKey, transportProfileKey)) { + return localRef; + } + disableGlobally("conflicting transport profile"); + return null; + } + } + + TelemetryManager candidate = + createManager(preliminaryConfig, transportProfileKey, httpTransportSupplier, false); + if (candidate == null) { + return null; + } + + TelemetryManager active; + TelemetryManager toCloseFirst = null; + TelemetryManager toCloseSecond = null; + boolean newlyDisabledConflict = false; + synchronized (TelemetryManager.class) { + if (globallyDisabled) { + active = null; + toCloseFirst = candidate; + } else if (instance == null) { + registerShutdownHook(); + instance = candidate; + active = candidate; + } else if (Objects.equals(instance.transportProfileKey, transportProfileKey)) { + instance.provisional = false; + active = instance; + toCloseFirst = candidate; + } else if (instance.provisional) { + toCloseFirst = instance; + registerShutdownHook(); + instance = candidate; + active = candidate; + } else { + newlyDisabledConflict = true; + globallyDisabled = true; + toCloseFirst = instance; + toCloseSecond = candidate; + instance = null; + active = null; + } + } + if (newlyDisabledConflict) { + logger.log( + Level.FINE, "Diagnostic telemetry disabled globally: conflicting transport profile"); + } + closeQuietly(toCloseFirst, false); + closeQuietly(toCloseSecond, false); + return active; } - private static TelemetryManager initializeWithConfig(TelemetryConfiguration preliminaryConfig) { + /** + * Returns an active {@link TelemetryManager} matching the failed connection's transport profile, + * or creates a provisional instance if none exists yet. + * + *

Opt-out disables telemetry globally. A transport-profile mismatch on a failed connection + * skips recording without disabling an active manager. + */ + @InternalApi + public static TelemetryManager getForFailedConnection( + Boolean enabledOverride, + String transportProfileKey, + Supplier httpTransportSupplier) { + if (globallyDisabled) { + return null; + } + TelemetryConfiguration preliminaryConfig = + TelemetryConfiguration.builder().resolveEnabled(enabledOverride).build(); if (!preliminaryConfig.isEnabled()) { disableGlobally("opt-out configuration"); return null; @@ -88,15 +234,14 @@ private static TelemetryManager initializeWithConfig(TelemetryConfiguration prel TelemetryManager localRef = instance; if (localRef != null) { - return localRef; + return Objects.equals(localRef.transportProfileKey, transportProfileKey) ? localRef : null; } - TelemetryConfiguration config = - preliminaryConfig.toBuilder() - .setDriverEnvironment(DriverEnvironmentDetector.build()) - .build(); - ClearcutTransport transport = new ClearcutTransport(config); - TelemetryManager candidate = new TelemetryManager(new TelemetryBatcher(config, transport)); + TelemetryManager candidate = + createManager(preliminaryConfig, transportProfileKey, httpTransportSupplier, true); + if (candidate == null) { + return null; + } TelemetryManager active; boolean closeCandidate = false; @@ -104,15 +249,14 @@ private static TelemetryManager initializeWithConfig(TelemetryConfiguration prel if (globallyDisabled) { active = null; closeCandidate = true; - } else if (instance != null) { - active = instance; - closeCandidate = true; - } else { - // Registered before the instance is published so that a non-null instance always implies a - // registered shutdown hook. + } else if (instance == null) { registerShutdownHook(); instance = candidate; active = candidate; + } else { + closeCandidate = true; + active = + Objects.equals(instance.transportProfileKey, transportProfileKey) ? instance : null; } } if (closeCandidate) { @@ -121,6 +265,49 @@ private static TelemetryManager initializeWithConfig(TelemetryConfiguration prel return active; } + private static TelemetryManager createManager( + TelemetryConfiguration preliminaryConfig, + String transportProfileKey, + Supplier httpTransportSupplier, + boolean provisional) { + HttpTransport httpTransport; + if (httpTransportSupplier != null) { + try { + httpTransport = httpTransportSupplier.get(); + } catch (Throwable t) { + logger.log(Level.FINE, "Failed to initialize Clearcut HTTP transport", t); + return null; + } + if (httpTransport == null) { + return null; + } + } else { + httpTransport = new NetHttpTransport(); + } + + try { + TelemetryConfiguration config = + preliminaryConfig.toBuilder() + .setDriverEnvironment(DriverEnvironmentDetector.build()) + .build(); + ClearcutTransport transport = new ClearcutTransport(httpTransport, config); + TelemetryBatcher batcher = new TelemetryBatcher(config, transport); + return new TelemetryManager(batcher, transportProfileKey, provisional); + } catch (Throwable t) { + logger.log(Level.FINE, "Failed to initialize TelemetryManager", t); + shutdownTransportQuietly(httpTransport); + return null; + } + } + + private static void shutdownTransportQuietly(HttpTransport httpTransport) { + try { + httpTransport.shutdown(); + } catch (Throwable t) { + logger.log(Level.FINE, "Error shutting down Clearcut HTTP transport", t); + } + } + /** Returns {@code true} if diagnostic telemetry has been permanently disabled for this JVM. */ @InternalApi public static boolean isGloballyDisabled() { @@ -153,7 +340,8 @@ static void init(TelemetryConfiguration config, ClearcutTransport transport) { if (globallyDisabled || config == null || !config.isEnabled() || transport == null) { return; } - TelemetryManager candidate = new TelemetryManager(new TelemetryBatcher(config, transport)); + TelemetryManager candidate = + new TelemetryManager(new TelemetryBatcher(config, transport), null, false); TelemetryManager toClose; boolean flushOld; synchronized (TelemetryManager.class) { @@ -232,7 +420,13 @@ public void close() { batcher.close(); } + @VisibleForTesting + static TelemetryManager getActiveInstanceForTest() { + return instance; + } + // Package-private test helper to reset the global kill switch between test runs + @VisibleForTesting static synchronized void resetGlobalDisableForTest() { globallyDisabled = false; } From 8cb68c08fc037921a4e8d382c98288c4302a8389 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:21:54 +0000 Subject: [PATCH 3/7] fix(bigquery-jdbc): propagate proxy and SSL TrustStore config to Clearcut transport --- .../jdbc/BigQueryJdbcDiagnosticTelemetry.java | 175 ++++++++++++++++-- .../jdbc/BigQueryJdbcProxyUtility.java | 125 ++++++++----- 2 files changed, 245 insertions(+), 55 deletions(-) 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 index 06961e9e3a4d..179ed1bc2a7a 100644 --- 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 @@ -16,27 +16,46 @@ 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.security.KeyStore; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; /** - * Coordinates Clearcut diagnostic telemetry eligibility and lifecycle transitions for BigQuery JDBC - * connections. + * Coordinates Clearcut diagnostic telemetry eligibility, transport-profile isolation, and lifecycle + * transitions for BigQuery JDBC connections. */ final class BigQueryJdbcDiagnosticTelemetry { + private static final String[] RAW_TRANSPORT_PROPERTY_NAMES = { + BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME + }; + private BigQueryJdbcDiagnosticTelemetry() {} /** - * Initializes Clearcut diagnostic telemetry for an eligible connection, or permanently disables - * it if the connection opts out or targets a non-default universe or endpoint override. + * 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 established transport profile. */ - static void initializeOrDisable(DataSource ds, Credentials credentials) { + static void initializeOrDisable( + DataSource ds, Map proxyProperties, Credentials credentials) { if (TelemetryManager.isGloballyDisabled()) { return; } @@ -46,13 +65,24 @@ static void initializeOrDisable(DataSource ds, Credentials credentials) { TelemetryManager.disableGlobally("non-default universe or endpoint override"); return; } - TelemetryManager.initializeForConnection(ds.getEnableDiagnosticTelemetry()); + String profileKey = + computeTransportProfileKey( + proxyProperties, + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider()); + TelemetryManager.initializeForConnection( + ds.getEnableDiagnosticTelemetry(), + profileKey, + createTransportSupplier(profileKey, proxyProperties, ds)); }); } /** * Enforces suppression and opt-out rules on failed {@link BigQueryDriver#connect} calls and - * records a failed connection attempt when diagnostic telemetry is eligible. + * 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) { @@ -63,8 +93,8 @@ static void recordFailedConnection( () -> { TelemetryManager manager = ds != null - ? initializeOrDisableForFailedDataSource(ds) - : initializeOrDisableFromRawUri(connectionUri); + ? getOrDisableForFailedDataSource(ds) + : getOrDisableFromRawUri(connectionUri); if (manager != null) { TelemetryManager.recordConnectionAttempt( Status.STATUS_ERROR, TelemetryManager.extractErrorCode(failure), authType); @@ -72,15 +102,34 @@ static void recordFailedConnection( }); } - private static TelemetryManager initializeOrDisableForFailedDataSource(DataSource ds) { + private static TelemetryManager getOrDisableForFailedDataSource(DataSource ds) { if (isSuppressed(ds, null)) { TelemetryManager.disableGlobally("non-default universe or endpoint override"); return null; } - return TelemetryManager.initializeForConnection(ds.getEnableDiagnosticTelemetry()); + Boolean explicitEnabled = ds.getEnableDiagnosticTelemetry(); + if (!explicitEnabled) { + TelemetryManager.disableGlobally("opt-out configuration"); + return null; + } + Optional> parsedProxy = + BigQueryJdbcProxyUtility.tryParseProxyProperties(ds); + if (!parsedProxy.isPresent()) { + return null; + } + Map proxyProperties = parsedProxy.get(); + String profileKey = + computeTransportProfileKey( + proxyProperties, + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider()); + return TelemetryManager.getForFailedConnection( + explicitEnabled, profileKey, createTransportSupplier(profileKey, proxyProperties, ds)); } - private static TelemetryManager initializeOrDisableFromRawUri(String connectionUri) { + private static TelemetryManager getOrDisableFromRawUri(String connectionUri) { if (isSuppressedFromRawUri(connectionUri)) { TelemetryManager.disableGlobally("non-default universe or endpoint override"); return null; @@ -101,8 +150,44 @@ private static TelemetryManager initializeOrDisableFromRawUri(String connectionU TelemetryManager.disableGlobally("invalid EnableDiagnosticTelemetry value"); return null; } + if (!explicitEnabled) { + TelemetryManager.disableGlobally("opt-out configuration"); + return null; + } + } + if (hasRawProxyOrTrustStore(connectionUri)) { + return null; + } + return TelemetryManager.getForFailedConnection(explicitEnabled, null, null); + } + + private static Supplier createTransportSupplier( + String profileKey, Map proxyProperties, DataSource ds) { + if (profileKey == null) { + return null; + } + return () -> + BigQueryJdbcProxyUtility.createCustomHttpTransport( + proxyProperties, + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider(), + BigQueryJdbcDiagnosticTelemetry.class.getName()); + } + + private static boolean hasRawProxyOrTrustStore(String connectionUri) { + try { + for (String property : RAW_TRANSPORT_PROPERTY_NAMES) { + if (BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(connectionUri, property) + != null) { + return true; + } + } + return false; + } catch (RuntimeException e) { + return true; } - return TelemetryManager.initializeForConnection(explicitEnabled); } private static Boolean parseStrictBoolean(String rawValue) { @@ -184,4 +269,68 @@ private static boolean isNonDefaultUniverse(String universeDomain) { private static boolean isNonBlank(String value) { return value != null && !value.trim().isEmpty(); } + + private static String normalizeBlankToNull(String value) { + if (value == null) { + return null; + } + String trimmed = value.trim(); + return trimmed.isEmpty() ? null : trimmed; + } + + 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; + } + String normalizedHost = + hasProxy + ? proxyProperties + .get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME) + .trim() + .toLowerCase(Locale.ROOT) + : null; + String normalizedPort = + hasProxy + ? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME).trim() + : null; + String normalizedTrustStoreType = null; + String normalizedTrustStoreProvider = null; + if (hasSsl) { + String explicitType = normalizeBlankToNull(sslTrustStoreType); + normalizedTrustStoreType = explicitType != null ? explicitType : KeyStore.getDefaultType(); + normalizedTrustStoreProvider = normalizeBlankToNull(sslTrustStoreProvider); + } + + Hasher hasher = Hashing.sha256().newHasher(); + putLengthPrefixed(hasher, normalizedHost); + putLengthPrefixed(hasher, normalizedPort); + 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, normalizedTrustStoreType); + putLengthPrefixed(hasher, normalizedTrustStoreProvider); + 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); + } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtility.java index bf676681e0fa..2fcfd6f81ec1 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtility.java @@ -41,6 +41,7 @@ import java.security.Provider; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; @@ -64,6 +65,7 @@ final class BigQueryJdbcProxyUtility { new BigQueryJdbcCustomLogger(BigQueryJdbcProxyUtility.class.getName()); static final String validPortRegex = "^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; + private static final Pattern VALID_PORT_PATTERN = Pattern.compile(validPortRegex); private static final String[] DEFAULT_CONSCRYPT_NAMED_GROUPS = new String[] {"X25519MLKEM768", "MLKEM1024", "X25519", "secp256r1", "secp384r1"}; private static final Provider CONSCRYPT_PROVIDER = createConscryptProvider(); @@ -102,60 +104,78 @@ protected void prepareSocket(SSLSocket socket) throws IOException { static Map parseProxyProperties(DataSource ds, String callerClassName) { LOG.finest("++enter++\t" + callerClassName); - Map proxyProperties = new HashMap<>(); - String proxyHost = ds.getProxyHost(); - if (proxyHost != null) { - proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, proxyHost); + String validationError = + validateProxyProperties( + ds.getProxyHost(), ds.getProxyPort(), ds.getProxyUid(), ds.getProxyPwd(), false); + if (validationError != null) { + IllegalArgumentException ex = new IllegalArgumentException(validationError); + LOG.severe(ex.getMessage(), ex); + throw ex; } - String proxyPort = ds.getProxyPort(); - if (proxyPort != null) { - if (!Pattern.compile(validPortRegex).matcher(proxyPort).find()) { - IllegalArgumentException ex = - new IllegalArgumentException( - String.format( - "Illegal port number provided %s. Please provide a valid port number.", - proxyPort)); - LOG.severe(ex.getMessage(), ex); - throw ex; - } - proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, proxyPort); + return buildProxyPropertiesMap( + ds.getProxyHost(), ds.getProxyPort(), ds.getProxyUid(), ds.getProxyPwd()); + } + + /** + * Validates and extracts proxy properties without logging {@code SEVERE} errors. Returns {@link + * Optional#empty()} if the proxy configuration is incomplete or invalid. + */ + static Optional> tryParseProxyProperties(DataSource ds) { + String validationError = + validateProxyProperties( + ds.getProxyHost(), ds.getProxyPort(), ds.getProxyUid(), ds.getProxyPwd(), true); + if (validationError != null) { + return Optional.empty(); } - String proxyUid = ds.getProxyUid(); - if (proxyUid != null) { - proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, proxyUid); + return Optional.of( + buildProxyPropertiesMap( + ds.getProxyHost(), ds.getProxyPort(), ds.getProxyUid(), ds.getProxyPwd())); + } + + private static String validateProxyProperties( + String proxyHost, + String proxyPort, + String proxyUid, + String proxyPwd, + boolean rejectBlankHost) { + if (proxyPort != null && !VALID_PORT_PATTERN.matcher(proxyPort).find()) { + return String.format( + "Illegal port number provided %s. Please provide a valid port number.", proxyPort); } - String proxyPwd = ds.getProxyPwd(); - if (proxyPwd != null) { - proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, proxyPwd); + if (rejectBlankHost && proxyHost != null && proxyHost.trim().isEmpty()) { + return "ProxyHost must not be blank."; } - boolean isMissingProxyHostOrPortWhenProxySet = (proxyHost == null && proxyPort != null) || (proxyHost != null && proxyPort == null); if (isMissingProxyHostOrPortWhenProxySet) { - IllegalArgumentException ex = - new IllegalArgumentException( - "Both ProxyHost and ProxyPort parameters need to be specified. No defaulting behavior" - + " occurs."); - LOG.severe(ex.getMessage(), ex); - throw ex; + return "Both ProxyHost and ProxyPort parameters need to be specified. No defaulting behavior" + + " occurs."; } boolean isMissingProxyUidOrPwdWhenAuthSet = (proxyUid == null && proxyPwd != null) || (proxyUid != null && proxyPwd == null); if (isMissingProxyUidOrPwdWhenAuthSet) { - IllegalArgumentException ex = - new IllegalArgumentException( - "Both ProxyUid and ProxyPwd parameters need to be specified for authentication."); - LOG.severe(ex.getMessage(), ex); - throw ex; + return "Both ProxyUid and ProxyPwd parameters need to be specified for authentication."; } - boolean isProxyAuthSetWithoutProxySettings = proxyUid != null && proxyHost == null; - if (isProxyAuthSetWithoutProxySettings) { - IllegalArgumentException ex = - new IllegalArgumentException( - "Proxy authentication provided via connection string with no proxy host or port" - + " set."); - LOG.severe(ex.getMessage(), ex); - throw ex; + if (proxyUid != null && proxyHost == null) { + return "Proxy authentication provided via connection string with no proxy host or port set."; + } + return null; + } + + private static Map buildProxyPropertiesMap( + String proxyHost, String proxyPort, String proxyUid, String proxyPwd) { + Map proxyProperties = new HashMap<>(); + if (proxyHost != null) { + proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, proxyHost); + } + if (proxyPort != null) { + proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, proxyPort); + } + if (proxyUid != null) { + proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, proxyUid); + } + if (proxyPwd != null) { + proxyProperties.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, proxyPwd); } return proxyProperties; } @@ -204,6 +224,27 @@ static HttpTransportOptions getHttpTransportOptions( return httpTransportOptionsBuilder.build(); } + /** + * Builds a dedicated {@link HttpTransport} configured with the given proxy and SSL TrustStore + * settings. Callers own the returned transport and are responsible for shutting it down. + */ + static HttpTransport createCustomHttpTransport( + Map proxyProperties, + String sslTrustStorePath, + String sslTrustStorePassword, + String sslTrustStoreType, + String sslTrustStoreProvider, + String callerClassName) { + return getHttpTransportFactory( + proxyProperties, + sslTrustStorePath, + sslTrustStorePassword, + sslTrustStoreType, + sslTrustStoreProvider, + callerClassName) + .create(); + } + private static HttpTransportFactory getHttpTransportFactory( Map proxyProperties, String sslTrustStorePath, From 595470f5874b6a590afcd42dcfb1bc4bd723fa43 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:23:21 +0000 Subject: [PATCH 4/7] test(bigquery-jdbc): verify loopback proxy and TrustStore Clearcut routing and failure isolation --- .../bigquery/jdbc/BigQueryDriverTest.java | 432 ++++++++++++++++++ 1 file changed, 432 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 783d077846c6..928dba9e1724 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,31 +24,56 @@ 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.sun.net.httpserver.HttpExchange; +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.Locale; import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; 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; @@ -617,6 +642,216 @@ public void testConnect_nullUrlDoesNotInitializeTelemetry() { assertThat(TelemetryManager.isInitialized()).isFalse(); } + @Test + public void testConnect_authenticatedProxyAndTrustStore_routesClearcutAndReusesTransport() + throws Exception { + try (LoopbackHttpsServer httpsServer = new LoopbackHttpsServer(); + LoopbackConnectProxy proxy = new LoopbackConnectProxy("proxyUser", "proxyPass")) { + String url = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", proxy.getPort()) + .append("ProxyUid", "proxyUser") + .append("ProxyPwd", "proxyPass") + .append("SSLTrustStore", getTestResourcePath("localhost-truststore.jks")) + .append("SSLTrustStorePwd", "changeit") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + try (Connection conn = bigQueryDriver.connect(url, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + HttpTransport firstTransport = TelemetryTestUtils.getActiveHttpTransport(); + assertThat(firstTransport).isInstanceOf(Apache5HttpTransport.class); + + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + httpsServer.getUrl(), TelemetryPayload.getDefaultInstance())) + .isTrue(); + assertThat(proxy.getAuthorizedConnects()).isEqualTo(1); + assertThat(httpsServer.getHitCount()).isEqualTo(1); + assertThat(httpsServer.getLastLogRequest().getLogEventsCount()).isEqualTo(1); + + // Matching profile reuses the exact same active HttpTransport instance + try (Connection second = bigQueryDriver.connect(url, new Properties())) { + assertThat(second.isClosed()).isFalse(); + } + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(firstTransport); + } + } + + @Test + public void testConnect_conflictingProxyUserOrDirectProfile_disablesActiveTelemetry() + throws Exception { + String trustStorePath = getTestResourcePath("localhost-truststore.jks"); + String userAUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", 8080) + .append("ProxyUid", "userA") + .append("ProxyPwd", "passA") + .append("SSLTrustStore", trustStorePath) + .append("SSLTrustStorePwd", "changeit") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + String userBUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", 8080) + .append("ProxyUid", "userB") + .append("ProxyPwd", "passB") + .append("SSLTrustStore", trustStorePath) + .append("SSLTrustStorePwd", "changeit") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + // Conflicting proxy user disables active proxied telemetry globally + try (Connection connA = bigQueryDriver.connect(userAUrl, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + try (Connection connB = bigQueryDriver.connect(userBUrl, new Properties())) { + assertThat(connB.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + + // Direct connect after proxied connect also disables globally + TelemetryTestUtils.reset(); + try (Connection proxied = bigQueryDriver.connect(userAUrl, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + try (Connection direct = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(direct.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + } + + @Test + public void testConnect_wrongProxyCredentials_failsClearcutUploadSilently() throws Exception { + try (LoopbackHttpsServer httpsServer = new LoopbackHttpsServer(); + LoopbackConnectProxy proxy = new LoopbackConnectProxy("proxyUser", "proxyPass")) { + String url = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", proxy.getPort()) + .append("ProxyUid", "proxyUser") + .append("ProxyPwd", "wrongPass") + .append("SSLTrustStore", getTestResourcePath("localhost-truststore.jks")) + .append("SSLTrustStorePwd", "changeit") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + try (Connection conn = bigQueryDriver.connect(url, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + httpsServer.getUrl(), TelemetryPayload.getDefaultInstance())) + .isFalse(); + assertThat(proxy.getRejectedConnects()).isAtLeast(1); + assertThat(httpsServer.getHitCount()).isEqualTo(0); + } + } + + @Test + public void testConnect_missingTrustStoreThroughProxy_failsTlsSilently() throws Exception { + try (LoopbackHttpsServer httpsServer = new LoopbackHttpsServer(); + LoopbackConnectProxy proxy = new LoopbackConnectProxy("proxyUser", "proxyPass")) { + String url = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", proxy.getPort()) + .append("ProxyUid", "proxyUser") + .append("ProxyPwd", "proxyPass") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + try (Connection conn = bigQueryDriver.connect(url, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat( + TelemetryTestUtils.sendWithActiveTransport( + httpsServer.getUrl(), TelemetryPayload.getDefaultInstance())) + .isFalse(); + assertThat(proxy.getAuthorizedConnects()).isEqualTo(1); + assertThat(httpsServer.getHitCount()).isEqualTo(0); + } + } + + @Test + public void testConnect_failedProxyOrTypoTrustStore_neverFallsBackOrDisablesActiveManager() + throws Exception { + String missingProxyPortUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + String typoTrustStoreUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("SSLTrustStore", "/nonexistent/typo-truststore.jks") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + // Fresh JVM: malformed proxy and nonexistent TrustStore do not fall back or disable globally + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(missingProxyPortUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(typoTrustStoreUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + + // Healthy direct connection followed by failed typo TrustStore keeps telemetry active + try (Connection direct = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + HttpTransport directTransport = TelemetryTestUtils.getActiveHttpTransport(); + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(typoTrustStoreUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(directTransport); + + // Healthy proxied connection followed by failed missing ProxyPort keeps proxied transport + TelemetryTestUtils.reset(); + String validProxiedUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("ProxyHost", "127.0.0.1") + .append("ProxyPort", 8080) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection proxied = bigQueryDriver.connect(validProxiedUrl, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + HttpTransport proxiedTransport = TelemetryTestUtils.getActiveHttpTransport(); + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(missingProxyPortUrl, new Properties())); + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(proxiedTransport); + + // Suppressed universe on a malformed-proxy failure still disables active commercial telemetry + String customUniverseBadProxyUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("universeDomain", CUSTOM_UNIVERSE_DOMAIN) + .append("ProxyHost", "127.0.0.1") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(customUniverseBadProxyUrl, new Properties())); + assertTelemetryDisabled(); + } + private static void assertTelemetryDisabled() { assertThat(TelemetryManager.isInitialized()).isFalse(); assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); @@ -628,4 +863,201 @@ private static Path writeServiceAccountJson(Path dir, String universeDomain) thr file, serviceAccountJson(universeDomain).toString().getBytes(StandardCharsets.UTF_8)); return file; } + + private static final class LoopbackHttpsServer implements AutoCloseable { + private final HttpsServer server; + private final AtomicInteger hitCount = new AtomicInteger(0); + private volatile LogRequest lastLogRequest; + + LoopbackHttpsServer() throws Exception { + KeyStore keyStore = KeyStore.getInstance("JKS"); + try (InputStream ksStream = getClass().getResourceAsStream("/localhost-keystore.jks")) { + keyStore.load(ksStream, "changeit".toCharArray()); + } + KeyManagerFactory kmf = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, "changeit".toCharArray()); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), null, null); + + server = HttpsServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + server.createContext("/log", this::handleLogRequest); + server.start(); + } + + private void handleLogRequest(HttpExchange exchange) throws IOException { + byte[] body = readAllBytes(exchange.getRequestBody()); + lastLogRequest = LogRequest.parseFrom(body); + hitCount.incrementAndGet(); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + } + + private static byte[] readAllBytes(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + } + return output.toByteArray(); + } + + String getUrl() { + return "https://localhost:" + server.getAddress().getPort() + "/log"; + } + + int getHitCount() { + return hitCount.get(); + } + + LogRequest getLastLogRequest() { + return lastLogRequest; + } + + @Override + public void close() { + server.stop(0); + } + } + + private static final class LoopbackConnectProxy implements AutoCloseable { + private final ServerSocket serverSocket; + private final ExecutorService executor = Executors.newCachedThreadPool(); + private final Set activeSockets = ConcurrentHashMap.newKeySet(); + private final String expectedAuthHeader; + private final AtomicInteger authorizedConnects = new AtomicInteger(0); + private final AtomicInteger rejectedConnects = new AtomicInteger(0); + + LoopbackConnectProxy(String username, String password) throws IOException { + String token = + Base64.getEncoder() + .encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); + this.expectedAuthHeader = "Basic " + token; + this.serverSocket = new ServerSocket(0, 16, InetAddress.getLoopbackAddress()); + executor.submit(this::acceptLoop); + } + + int getPort() { + return serverSocket.getLocalPort(); + } + + int getAuthorizedConnects() { + return authorizedConnects.get(); + } + + int getRejectedConnects() { + return rejectedConnects.get(); + } + + private void acceptLoop() { + while (!serverSocket.isClosed()) { + try { + Socket client = serverSocket.accept(); + activeSockets.add(client); + executor.submit(() -> handleClient(client)); + } catch (IOException ignored) { + return; + } + } + } + + private void handleClient(Socket client) { + try { + BufferedReader reader = + new BufferedReader( + new InputStreamReader(client.getInputStream(), StandardCharsets.US_ASCII)); + String requestLine = reader.readLine(); + if (requestLine == null || !requestLine.startsWith("CONNECT ")) { + return; + } + String[] parts = requestLine.split(" "); + if (parts.length < 2) { + return; + } + String[] hostPort = parts[1].split(":"); + String targetHost = hostPort[0]; + int targetPort = Integer.parseInt(hostPort[1]); + + String proxyAuth = null; + String line; + while ((line = reader.readLine()) != null && !line.isEmpty()) { + if (line.toLowerCase(Locale.ROOT).startsWith("proxy-authorization:")) { + proxyAuth = line.substring("proxy-authorization:".length()).trim(); + } + } + + OutputStream clientOut = client.getOutputStream(); + if (!expectedAuthHeader.equals(proxyAuth)) { + if (proxyAuth != null) { + rejectedConnects.incrementAndGet(); + } + 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(targetHost, targetPort)) { + activeSockets.add(upstream); + try { + clientOut.write( + "HTTP/1.1 200 Connection Established\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + clientOut.flush(); + Thread forward = new Thread(() -> copyQuietly(client, upstream)); + forward.setDaemon(true); + forward.start(); + copyQuietly(upstream, client); + forward.join(2000); + } finally { + activeSockets.remove(upstream); + } + } + } catch (Exception ignored) { + // Expected on client disconnect or TLS handshake rejection + } finally { + activeSockets.remove(client); + closeSocketQuietly(client); + } + } + + private static void copyQuietly(Socket from, Socket to) { + try { + InputStream in = from.getInputStream(); + OutputStream out = to.getOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + out.flush(); + } + } catch (IOException ignored) { + // Tunnel closed + } + } + + private static void closeSocketQuietly(Socket socket) { + try { + socket.close(); + } catch (IOException ignored) { + // Best-effort cleanup + } + } + + @Override + public void close() throws IOException { + serverSocket.close(); + for (Socket socket : activeSockets) { + closeSocketQuietly(socket); + } + activeSockets.clear(); + executor.shutdownNow(); + } + } } From 369cb315f6840620aa2e052e5410e49a0ff53d6c Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:25:01 +0000 Subject: [PATCH 5/7] test(bigquery-jdbc): cover proxy validation, normalized profile keys, and failed-connect isolation --- .../bigquery/jdbc/BigQueryJdbcBaseTest.java | 11 ++ .../BigQueryJdbcDiagnosticTelemetryTest.java | 155 ++++++++++++++++++ .../jdbc/BigQueryJdbcProxyUtilityTest.java | 44 +++++ 3 files changed, 210 insertions(+) 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 66003e92b7f0..85b55810f394 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 @@ -22,7 +22,10 @@ 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; import org.junit.jupiter.api.AfterEach; @@ -124,4 +127,12 @@ protected static JsonObject serviceAccountJson(String universeDomain) { 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 index 24ed6429aadd..881dfdb8fe86 100644 --- 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 @@ -18,8 +18,10 @@ 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.auth.Credentials; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.ComputeEngineCredentials; @@ -33,7 +35,9 @@ import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.security.KeyStore; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; @@ -178,6 +182,157 @@ public void testRecordFailedConnection_rawUriSuppressionAndInvalidOptOutDisables assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); } + @Test + public void testComputeTransportProfileKey_differentiatesActiveFieldsAndNormalizesEquivalents() { + // Direct connection returns null even if unused TrustStore metadata is present + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + Collections.emptyMap(), null, "unused-pwd", "JKS", "SUN")) + .isNull(); + + Map proxyA = new HashMap<>(); + proxyA.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, "proxy.example.com"); + proxyA.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, "8080"); + proxyA.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, "userA"); + proxyA.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, "passA"); + + String baseline = + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/path/a.jks", "pwdA", KeyStore.getDefaultType(), null); + assertThat(baseline).isNotNull(); + + // Equivalent normalized host/port casing, whitespace, and default TrustStore type/provider + Map proxyNormalized = new HashMap<>(); + proxyNormalized.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, " PROXY.EXAMPLE.COM "); + proxyNormalized.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, " 8080 "); + proxyNormalized.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, "userA"); + proxyNormalized.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, "passA"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyNormalized, "/path/a.jks", "pwdA", " ", "")) + .isEqualTo(baseline); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyNormalized, "/path/a.jks", "pwdA", null, null)) + .isEqualTo(baseline); + + // Every active field change produces a distinct profile key + Map diffHost = new HashMap<>(proxyA); + diffHost.put(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, "proxy2.example.com"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + diffHost, "/path/a.jks", "pwdA", KeyStore.getDefaultType(), null)) + .isNotEqualTo(baseline); + + Map diffPort = new HashMap<>(proxyA); + diffPort.put(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, "8081"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + diffPort, "/path/a.jks", "pwdA", KeyStore.getDefaultType(), null)) + .isNotEqualTo(baseline); + + Map diffUser = new HashMap<>(proxyA); + diffUser.put(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, "userB"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + diffUser, "/path/a.jks", "pwdA", KeyStore.getDefaultType(), null)) + .isNotEqualTo(baseline); + + Map diffPwd = new HashMap<>(proxyA); + diffPwd.put(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, "passB"); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + diffPwd, "/path/a.jks", "pwdA", KeyStore.getDefaultType(), null)) + .isNotEqualTo(baseline); + + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/path/b.jks", "pwdA", KeyStore.getDefaultType(), null)) + .isNotEqualTo(baseline); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/path/a.jks", "pwdB", KeyStore.getDefaultType(), null)) + .isNotEqualTo(baseline); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/path/a.jks", "pwdA", "PKCS12", null)) + .isNotEqualTo(baseline); + assertThat( + BigQueryJdbcDiagnosticTelemetry.computeTransportProfileKey( + proxyA, "/path/a.jks", "pwdA", KeyStore.getDefaultType(), "SUN")) + .isNotEqualTo(baseline); + } + + @Test + public void testRecordFailedConnection_typoTrustStoreAfterHealthyDirectKeepsTelemetryActive() { + assertThat(TelemetryManager.getInstance()).isNotNull(); + assertThat(TelemetryManager.isInitialized()).isTrue(); + + DataSource typoDs = new DataSource(); + typoDs.setSSLTrustStorePath("/nonexistent/typo-truststore.jks"); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + RAW_URI_PREFIX + ";SSLTrustStore=/nonexistent/typo-truststore.jks;", + typoDs, + AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, + new RuntimeException("truststore not found")); + + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "ProxyHost=127.0.0.1;", + "ProxyHost=127.0.0.1;ProxyPort=8080;", + "SSLTrustStore=/path/to/truststore.jks;", + "ProxyPwd=bad%pass;" + }) + public void testRecordFailedConnection_rawUriWithProxyOrTrustStoreSkipsWithoutKillingActive( + String rawSuffix) { + String rawUri = RAW_URI_PREFIX + ";" + rawSuffix; + + // Fresh JVM: does not initialize a direct Clearcut transport + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + + // Active proxied manager: remains active and untouched + HttpTransport activeTransport = mock(HttpTransport.class); + assertThat( + TelemetryManager.initializeForConnection( + Boolean.TRUE, "proxy-profile", () -> activeTransport)) + .isNotNull(); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + assertThat(TelemetryManager.isInitialized()).isTrue(); + assertThat(TelemetryManager.isGloballyDisabled()).isFalse(); + assertThat(TelemetryTestUtils.getActiveHttpTransport()).isSameInstanceAs(activeTransport); + } + + @Test + public void testRecordFailedConnection_parsedDataSourceOptOutWithMalformedProxyDisablesActive() { + HttpTransport activeTransport = mock(HttpTransport.class); + assertThat( + TelemetryManager.initializeForConnection( + Boolean.TRUE, "proxy-profile", () -> activeTransport)) + .isNotNull(); + + DataSource optOutMalformedProxyDs = new DataSource(); + optOutMalformedProxyDs.setEnableDiagnosticTelemetry(false); + optOutMalformedProxyDs.setProxyHost("127.0.0.1"); // Missing ProxyPort + + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + RAW_URI_PREFIX + ";ProxyHost=127.0.0.1;EnableDiagnosticTelemetry=0;", + optOutMalformedProxyDs, + AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, + new RuntimeException("invalid proxy")); + + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + private static ServiceAccountCredentials buildServiceAccountCredentials(String universeDomain) throws IOException { return ServiceAccountCredentials.fromStream( diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtilityTest.java index 6aa8dd20e217..1e495232a0b2 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcProxyUtilityTest.java @@ -50,6 +50,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; @@ -146,6 +147,49 @@ public void testMissingPwdWithUidThrowsIllegalArgument() { null)); } + @Test + public void testTryParseProxyProperties_validAndInvalidConfigurations() { + assertThat(BigQueryJdbcProxyUtility.tryParseProxyProperties(new DataSource())) + .isEqualTo(Optional.of(Collections.emptyMap())); + + DataSource validDs = new DataSource(); + validDs.setProxyHost("127.0.0.1"); + validDs.setProxyPort("8080"); + validDs.setProxyUid("user"); + validDs.setProxyPwd("pass"); + Optional> valid = BigQueryJdbcProxyUtility.tryParseProxyProperties(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"); + + DataSource blankHost = new DataSource(); + blankHost.setProxyHost(" "); + blankHost.setProxyPort("8080"); + assertThat(BigQueryJdbcProxyUtility.tryParseProxyProperties(blankHost).isPresent()).isFalse(); + + DataSource missingPort = new DataSource(); + missingPort.setProxyHost("127.0.0.1"); + assertThat(BigQueryJdbcProxyUtility.tryParseProxyProperties(missingPort).isPresent()).isFalse(); + + DataSource badPort = new DataSource(); + badPort.setProxyHost("127.0.0.1"); + badPort.setProxyPort("99999"); + assertThat(BigQueryJdbcProxyUtility.tryParseProxyProperties(badPort).isPresent()).isFalse(); + + DataSource missingPwd = new DataSource(); + missingPwd.setProxyHost("127.0.0.1"); + missingPwd.setProxyPort("8080"); + missingPwd.setProxyUid("user"); + assertThat(BigQueryJdbcProxyUtility.tryParseProxyProperties(missingPwd).isPresent()).isFalse(); + + DataSource authOnly = new DataSource(); + authOnly.setProxyUid("user"); + authOnly.setProxyPwd("pass"); + assertThat(BigQueryJdbcProxyUtility.tryParseProxyProperties(authOnly).isPresent()).isFalse(); + } + @Test public void testGetHttpTransportOptionsWithAuthenticatedProxy() { String connection_uri = From 128471331270619d6d36360a2bbf5d7b187cf2ba Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:26:14 +0000 Subject: [PATCH 6/7] test(bigquery-jdbc): verify owned ClearcutTransport shutdown in transport and batcher tests --- .../telemetry/v1/ClearcutTransportTest.java | 22 +++++++++++++++++++ .../telemetry/v1/TelemetryBatcherTest.java | 18 +++++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransportTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransportTest.java index 2e958cd7904e..b5911e25a965 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransportTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/ClearcutTransportTest.java @@ -19,7 +19,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.testing.http.MockHttpTransport; @@ -260,4 +264,22 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("executeQuery", error.getMethodName()); assertEquals(1, error.getCount()); } + + @Test + public void testClose_shutsDownTransportAndSwallowsErrors() throws Exception { + TelemetryConfiguration config = TelemetryConfiguration.newBuilder().setEnabled(true).build(); + + HttpTransport transport = mock(HttpTransport.class); + try (ClearcutTransport ignored = new ClearcutTransport(transport, config)) { + // Closed automatically at block exit + } + verify(transport).shutdown(); + + HttpTransport failingShutdown = mock(HttpTransport.class); + doThrow(new IOException("shutdown error")).when(failingShutdown).shutdown(); + try (ClearcutTransport ignored = new ClearcutTransport(failingShutdown, config)) { + // Shutdown exception must be swallowed + } + verify(failingShutdown).shutdown(); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcherTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcherTest.java index 38c6a00e9f55..4b16decc3c9c 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcherTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryBatcherTest.java @@ -21,9 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; @@ -520,7 +524,10 @@ public void testClose_doesNotWaitForUnresponsiveEndpoint() throws IOException { .build(); TelemetryBatcher batcher = new TelemetryBatcher( - configuration, new ClearcutTransport(configuration), executorService, true); + configuration, + new ClearcutTransport(new NetHttpTransport(), configuration), + executorService, + true); batcher.offer(featureNamed("testFeature")); long start = System.currentTimeMillis(); @@ -534,7 +541,8 @@ public void testClose_doesNotWaitForUnresponsiveEndpoint() throws IOException { } @Test - public void testCloseWithoutFlush_dropsBufferedMetricsAndSkipsFlush() { + public void testCloseWithoutFlush_dropsBufferedMetricsSkipsFlushAndShutsDownTransport() + throws Exception { AtomicInteger requestCount = new AtomicInteger(); MockHttpTransport mockTransport = new MockHttpTransport() { @@ -559,6 +567,12 @@ public LowLevelHttpRequest buildRequest(String method, String url) { assertFalse(batcher.flush().isSuccess()); assertEquals(0, requestCount.get()); assertTrue(executorService.isShutdown()); + + HttpTransport owned = mock(HttpTransport.class); + TelemetryBatcher ownedBatcher = + new TelemetryBatcher(config, new ClearcutTransport(owned, config), null, false); + ownedBatcher.close(false); + verify(owned).shutdown(); } @Test From de8bc7a08458b83b51e487cb26772e96a107cef1 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:27:00 +0000 Subject: [PATCH 7/7] test(bigquery-jdbc): verify transport profile isolation, provisional replacement, and transport shutdown --- .../telemetry/v1/TelemetryManagerTest.java | 163 +++++++++++++++++- .../jdbc/telemetry/v1/TelemetryTestUtils.java | 34 ++++ 2 files changed, 191 insertions(+), 6 deletions(-) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java index de9d66b2251b..a01d232b9b67 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java @@ -22,7 +22,12 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; @@ -57,7 +62,7 @@ public void testGetInstance_returnsSameSingletonInstance() { @Test public void testInit_withDisabledConfig_doesNotInitializeInstance() { TelemetryConfiguration config = TelemetryConfiguration.builder().setEnabled(false).build(); - ClearcutTransport transport = new ClearcutTransport(config); + ClearcutTransport transport = new ClearcutTransport(new MockHttpTransport(), config); TelemetryManager.init(config, transport); @@ -67,7 +72,7 @@ public void testInit_withDisabledConfig_doesNotInitializeInstance() { @Test public void testInit_withEnabledConfig_initializesCustomInstance() { TelemetryConfiguration config = TelemetryConfiguration.builder().setEnabled(true).build(); - ClearcutTransport transport = new ClearcutTransport(config); + ClearcutTransport transport = new ClearcutTransport(new MockHttpTransport(), config); TelemetryManager.init(config, transport); @@ -297,14 +302,160 @@ public LowLevelHttpRequest buildRequest(String method, String url) { @Test public void testInitializeForConnection_respectsTypedBooleanAndDisableGlobally() { - TelemetryManager active = TelemetryManager.initializeForConnection(Boolean.TRUE); + TelemetryManager active = TelemetryManager.initializeForConnection(Boolean.TRUE, null, null); assertNotNull(active); - assertSame(active, TelemetryManager.initializeForConnection(null)); + assertSame(active, TelemetryManager.initializeForConnection(null, null, null)); assertFalse(TelemetryManager.isGloballyDisabled()); - assertNull(TelemetryManager.initializeForConnection(Boolean.FALSE)); + assertNull(TelemetryManager.initializeForConnection(Boolean.FALSE, null, null)); assertFalse(TelemetryManager.isInitialized()); assertTrue(TelemetryManager.isGloballyDisabled()); - assertNull(TelemetryManager.initializeForConnection(Boolean.TRUE)); + assertNull(TelemetryManager.initializeForConnection(Boolean.TRUE, null, null)); + } + + @Test + public void testInitializeForConnection_reusesMatchingProfileAndInvokesSupplierOnce() + throws Exception { + HttpTransport transport = mock(HttpTransport.class); + AtomicInteger supplierCalls = new AtomicInteger(0); + + TelemetryManager first = + TelemetryManager.initializeForConnection( + Boolean.TRUE, + "profile-a", + () -> { + supplierCalls.incrementAndGet(); + return transport; + }); + TelemetryManager second = + TelemetryManager.initializeForConnection( + Boolean.TRUE, + "profile-a", + () -> { + supplierCalls.incrementAndGet(); + return mock(HttpTransport.class); + }); + + assertNotNull(first); + assertSame(first, second); + assertEquals(1, supplierCalls.get()); + assertSame(transport, first.getBatcher().getTransport().getHttpTransport()); + + TelemetryManager.closeInstance(); + verify(transport).shutdown(); + } + + @Test + public void testInitializeForConnection_conflictingEstablishedProfileDisablesAndShutsDown() + throws Exception { + HttpTransport firstTransport = mock(HttpTransport.class); + AtomicInteger secondSupplierCalls = new AtomicInteger(0); + + TelemetryManager first = + TelemetryManager.initializeForConnection(Boolean.TRUE, "profile-a", () -> firstTransport); + assertNotNull(first); + + TelemetryManager conflicting = + TelemetryManager.initializeForConnection( + Boolean.TRUE, + "profile-b", + () -> { + secondSupplierCalls.incrementAndGet(); + return mock(HttpTransport.class); + }); + + assertNull(conflicting); + assertFalse(TelemetryManager.isInitialized()); + assertTrue(TelemetryManager.isGloballyDisabled()); + assertEquals(0, secondSupplierCalls.get()); + verify(firstTransport).shutdown(); + assertNull( + TelemetryManager.initializeForConnection( + Boolean.TRUE, "profile-a", () -> mock(HttpTransport.class))); + } + + @Test + public void testInitializeForConnection_supplierOrSetupFailureCleansUpWithoutFallback() + throws Exception { + assertNull( + TelemetryManager.initializeForConnection( + Boolean.TRUE, + "profile-throw", + () -> { + throw new RuntimeException("simulated TrustStore failure"); + })); + assertFalse(TelemetryManager.isInitialized()); + + assertNull(TelemetryManager.initializeForConnection(Boolean.TRUE, "profile-null", () -> null)); + assertFalse(TelemetryManager.isInitialized()); + + // Post-supplier failure shuts down the newly created HttpTransport rather than leaking it + HttpTransport brokenTransport = mock(HttpTransport.class); + when(brokenTransport.createRequestFactory()).thenThrow(new RuntimeException("setup failure")); + assertNull( + TelemetryManager.initializeForConnection( + Boolean.TRUE, "profile-broken", () -> brokenTransport)); + assertFalse(TelemetryManager.isInitialized()); + verify(brokenTransport).shutdown(); + } + + @Test + public void testGetForFailedConnection_mismatchDoesNotDisableActiveAndProvisionalIsReplaced() + throws Exception { + // Active established manager is untouched by a failed connection with a different profile + HttpTransport establishedTransport = mock(HttpTransport.class); + TelemetryManager established = + TelemetryManager.initializeForConnection( + Boolean.TRUE, "profile-a", () -> establishedTransport); + assertNotNull(established); + + assertNull( + TelemetryManager.getForFailedConnection( + Boolean.TRUE, "profile-b", () -> mock(HttpTransport.class))); + assertTrue(TelemetryManager.isInitialized()); + assertFalse(TelemetryManager.isGloballyDisabled()); + verify(establishedTransport, never()).shutdown(); + + // Matching profile on a failed connection reuses the active manager + assertSame( + established, + TelemetryManager.getForFailedConnection( + Boolean.TRUE, "profile-a", () -> mock(HttpTransport.class))); + + // Failed first connection creates a provisional manager that is replaced without disabling + // when the first established connection uses a different profile + TelemetryTestUtils.reset(); + HttpTransport provisionalTransport = mock(HttpTransport.class); + TelemetryManager provisional = + TelemetryManager.getForFailedConnection( + Boolean.TRUE, "profile-failed-first", () -> provisionalTransport); + assertNotNull(provisional); + + HttpTransport realTransport = mock(HttpTransport.class); + TelemetryManager real = + TelemetryManager.initializeForConnection(Boolean.TRUE, "profile-real", () -> realTransport); + assertNotNull(real); + assertFalse(TelemetryManager.isGloballyDisabled()); + assertSame(realTransport, real.getBatcher().getTransport().getHttpTransport()); + verify(provisionalTransport).shutdown(); + } + + @Test + public void testGetInstance_legacyOverloadsPreserveActiveProxiedInstance() throws Exception { + HttpTransport proxied = mock(HttpTransport.class); + TelemetryManager active = + TelemetryManager.initializeForConnection(Boolean.TRUE, "proxy-profile", () -> proxied); + assertNotNull(active); + + assertSame(active, TelemetryManager.getInstance()); + assertSame(active, TelemetryManager.getInstance(new Properties())); + assertTrue(TelemetryManager.isInitialized()); + verify(proxied, never()).shutdown(); + + Properties optOut = new Properties(); + optOut.setProperty("EnableDiagnosticTelemetry", "0"); + assertNull(TelemetryManager.getInstance(optOut)); + assertTrue(TelemetryManager.isGloballyDisabled()); + verify(proxied).shutdown(); } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java index 3e0ee8ca12cc..0bb3ae3eb271 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.api.client.http.HttpTransport; import java.util.List; /** Test-only access to {@link TelemetryManager}'s package-private lifecycle state. */ @@ -40,6 +41,39 @@ public static void initCapturingPayloads(List captured) { TelemetryManager.init(config, transport); } + /** + * Returns the {@link HttpTransport} currently held by the active {@link TelemetryManager}, or + * {@code null} if telemetry is not initialized. + */ + public static HttpTransport getActiveHttpTransport() { + TelemetryManager manager = TelemetryManager.getActiveInstanceForTest(); + if (manager == null) { + return null; + } + TelemetryBatcher batcher = manager.getBatcher(); + if (batcher == null || batcher.getTransport() == null) { + return null; + } + return batcher.getTransport().getHttpTransport(); + } + + /** + * Sends a payload through the active {@link TelemetryManager}'s {@link HttpTransport} to a test + * endpoint URL without closing the transport. + * + * @return {@code true} if the Clearcut upload returned a 2xx response + */ + public static boolean sendWithActiveTransport(String endpointUrl, TelemetryPayload payload) { + HttpTransport activeTransport = getActiveHttpTransport(); + if (activeTransport == null) { + return false; + } + TelemetryConfiguration config = + TelemetryConfiguration.builder().setEnabled(true).setEndpointUrl(endpointUrl).build(); + ClearcutTransport transport = new ClearcutTransport(activeTransport, config); + return transport.send(payload).isSuccess(); + } + /** Flushes and closes the shared instance so captured payloads are delivered. */ public static void flush() { TelemetryManager.closeInstance();